我试图让这个程序逐行读取输入文件,然后将其打印到输出文件,例如:
输入文件包含:
cookies
cake
ice cream
我希望输出文件显示:
第1行:cookies
第2行:蛋糕
第3行:冰淇淋
我无法弄清楚如何做到这一点,所以任何帮助将不胜感激。
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.print("Enter the input file: ");
String name = in.next();
FileReader file = new FileReader(name);
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
while(line != null){
text += line;
line = reader.readLine();
}
reader.close();
System.out.print("Enter the output file: ");
String out = in.next();
FileWriter filew = new FileWriter(out);
BufferedWriter buffw = new BufferedWriter(filew);
buffw.write(text);
buffw.close();
System.out.print("File written!");
in.close();
}
}
答案 0 :(得分:1)
问题在于循环如:
while(line != null){
text += line;
line = reader.readLine();
}
readLine
方法会占用新行字符,因此您无法在输出文件中看到它。您需要在末尾附加一个新行字符,如:
while(line != null){
text += line;
text += '\n';
line = reader.readLine();
}
我建议您使用StringBuilder
而不是字符串连接,如:
StringBuilder stringBuilder = ...
while ..
stringBuilder.append(line);
stringBuilder.append('\n');
...
答案 1 :(得分:0)
您必须再次添加行尾字符,因为getSolutions
会将其删除:
readLine()