在输出文件“CMFTSwitchesnew.txt”中只有输入文件的最后一行。我已经测试了一些不同的方法,比如改变write.println(input.nextLine()),但我现在还不确定问题出在哪里。
package WorkingWithFiles;
import java.io.*;
import java.util.Scanner;
public class FileIO
{
public static void main(String[] args)
{
File output = new File("CMFTSwitchesNew.txt");
File source = new File("src/CMFTSwitches.txt");
try {
Scanner input = new Scanner(source);
while (input.hasNextLine()) {
try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
}
} catch (FileNotFoundException e) {
System.out.println("The file was not found");
}
}
}
答案 0 :(得分:0)
try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
您在每次迭代中创建PrintWriter而不使用允许您告知PrintWriter
在现有文件末尾附加数据的构造函数。这样您只能看到上次写入文件的输出。要么改为
PrintWriter write = new PrintWriter(output, true);
或在PrintWriter
循环之外实例化while
并在其后关闭它。