Java FileWriter如何写入下一行
我使用下面的代码将记录写入文件。记录可以写入文件中,但附加在一行中,每次我调用此方法示例:
Hello WorldHello WorldHello WorldHello World
如何修改代码,使输出如下所示,以便在读取文本时我可以使用 line.hasNextLine() 来检查?
你好世界
你好世界
你好世界
你好世界
// Create file
FileWriter fstream = new FileWriter(fileName, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(c.toString());
//Close the output stream
out.close();
// Code I used to read record I am using | as a seperator name and id
String fileName = folderPath + "listCatalogue.txt";
String line = "";
Scanner scanner;
String name, id;
scanner = new Scanner(fileName);
System.out.println(scanner.hasNextLine());
while (scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
StringTokenizer st = new StringTokenizer(line, "|");
name = st.nextToken();
id = st.nextToken();
catalogues.add(new Catalogue(name, id));
}
I used the code below to write record into a File. The record can be written in the file, but is append in one Line, each time I call this method example:
Hello WorldHello WorldHello WorldHello World
How can I modify the code so the output look like below, so that when read the text I can use line.hasNextLine() to check?
Hello World
Hello World
Hello World
Hello World
// Create file
FileWriter fstream = new FileWriter(fileName, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(c.toString());
//Close the output stream
out.close();
// Code I used to read record I am using | as a seperator name and id
String fileName = folderPath + "listCatalogue.txt";
String line = "";
Scanner scanner;
String name, id;
scanner = new Scanner(fileName);
System.out.println(scanner.hasNextLine());
while (scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
StringTokenizer st = new StringTokenizer(line, "|");
name = st.nextToken();
id = st.nextToken();
catalogues.add(new Catalogue(name, id));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不确定我的理解是否正确,但是这是你的意思吗?
I'm not sure if I understood correctly, but is this what you mean?
这是一个简单的解决方案,我希望它有效
编辑:
我使用的是“\n”,这显然不是推荐的方法,修改了答案。
here is a simple solution, I hope it works
EDIT:
I was using "\n" which was obviously not recommended approach, modified answer.
您可以调用java提供的方法
newLine()
,将新行插入到文件中。有关更多参考 -http ://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#newLine()
You can call the method
newLine()
provided by java, to insert the new line in to a file.For more refernce -http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#newLine()
如果您的系统属性 line.separator 正确,则 .newLine() 是最好的。
有时您不想更改属性runtime。
所以替代解决方案是附加 \n
.newLine() is the best if your system property line.separator is proper .
and sometime you don't want to change the property runtime .
So alternative solution is appending \n