好吧,我正在开发一个非常小的程序,旨在获取文本文件 test.txt 的内容,并将它们放入另一个空文件 testCopied.txt 中。诀窍是我想使用 Scanner 和 printWriter 因为我想更好地理解它们。
这是我的代码:
import java.io.*;
import java.util.*;
public class CopyA
{
public static void main(String [] args)
{
String Input_filename = args[0];
String Output_filename = args[1];
char r = args[2].charAt(0);
try
{
Scanner sc = new Scanner(new File(Input_filename));
FileWriter fw = new FileWriter(Output_filename);
PrintWriter printer = new PrintWriter(fw);
while(sc.hasNextLine())
{
String s = sc.nextLine();
printer.write(s);
}
sc.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
}
这可以编译,但是当我查看 testCopied.txt 时,它仍然是空白,并且没有将 test.txt 的内容传输到其中。我究竟做错了什么? Java IO 让我很困惑,所以我试图更好地掌握它。非常感谢任何帮助!
最佳答案
您错过了需要添加的 PrintWriter
对象的 flush
() 和 close
()
然后使用 System.getProperty("line.separator")
来使用行分隔符,同时将每一行写入第二个文件。
您可以引用以下代码:
PrintWriter printer = null;
Scanner sc = null;
try
{
String lineSeparator = System.getProperty("line.separator");
sc = new Scanner(new File(Input_filename));
FileWriter fw = new FileWriter(Output_filename);
printer = new PrintWriter(fw);
while(sc.hasNextLine())
{
String s = sc.nextLine()+lineSeparator; //Add line separator
printer.write(s);
}
}
catch(IOException ioe)
{
System.out.println(ioe);
} finally {
if(sc != null) {
sc.close();
}
if(printer != null) {
printer.flush();
printer.close();
}
}
此外,请确保始终关闭 finally
block 中的资源(您在代码中错过了 Scanner 对象)。
关于JavaIO : Using scanner and printWriter to copy the contents of a text file and put them in another text file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40598402/