试试下面的代码
import java.io.*;
import java.util.*;
/**
*
* @author Selva
*/
public class Readfile {
public static void main(String[] args) throws FileNotFoundException, IOException{
if (args.length==0)
{
System.out.println("Error: Bad command or filename.");
System.exit(0);
}else {
InputStream in = new FileInputStream(new File(args[0]));
OutputStream out = new FileOutputStream(new File(args[1]));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}
使用如果您的文本文件和 java 代码是同一文件夹运行此代码,则运行此代码,如下所示。
java Readfile input.txt output.txt
如果您的文本文件和 java 代码是不同的文件夹,请运行如下程序。
java Readfile c:\input.txt c:\output.txt
如果您使用扫描仪读取输入表单键盘。请尝试以下代码
import java.io.*;
import java.util.*;
/**
*
* @author Selva
*/
public class Readfile {
public static void main(String[] args) throws FileNotFoundException, IOException{
Scanner s=new Scanner(System.in);
if (args.length==0)
{
System.out.println("Error: Bad command or filename.");
System.exit(0);
}else {
System.out.println("Enter Input FileName");
String a=s.nextLine();
System.out.println("Enter Output FileName");
String b=s.nextLine();
InputStream in = new FileInputStream(new File(a));
OutputStream out = new FileOutputStream(new File(b));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}