好吧,所以我正在开发一个非常小的程序,旨在将文本文件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对我来说很混乱,因此我试图更好地掌握它。任何帮助,我们都感激不尽!
您错过了flush
()和close
()PrintWriter
所需添加的对象
然后System.getProperty("line.separator")
在将每一行写入第二个文件时使用行分隔符using 。
您可以参考以下代码:
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
块中的资源(您的代码中错过了Scanner对象的资源)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句