Java FileWriter如何写入下一行 [英] Java FileWriter how to write to next Line

查看:1474
本文介绍了Java FileWriter如何写入下一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的代码将记录写入文件。记录可以写在文件中,但是被追加到一行中,每次我调用这个方法的例子:

Hello WorldHello WorldHello WorldHello World



如何修改代码使得输出如下所示,以便在阅读文本时我可以使用line.hasNextLine()来检查?

Hello World

Hello World

Hello World

Hello World

  //创建文件
FileWriter fstream = new FileWriter(fileName,true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(c.toString());
//关闭输出流
out.close();

//代码我用来读取记录我正在使用|作为分隔符名称和id
String fileName = folderPath +listCatalogue.txt;
String line =;
扫描仪扫描仪;
字符串名称,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 Catalog(name,id));

$ / code>


解决方案

  out.write(c.toString()); 
out.newLine();

这里是一个简单的解决方案,我希望它可以工作

编辑:
我使用的是\\\
,这显然不是推荐的方法,修改后的答案。

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));
        }

解决方案

out.write(c.toString());
out.newLine();

here is a simple solution, I hope it works

EDIT: I was using "\n" which was obviously not recommended approach, modified answer.

这篇关于Java FileWriter如何写入下一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆