在Java中逐行读取文本文件

时间:2016-04-17 06:58:49

标签: java

如何逐行读取文本文件中的内容?当我尝试输出内容时,新行字符似乎被忽略了。

public class ReadFile {
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        String str= "";

        //Reading content from file
        Scanner in = new Scanner(new FileReader("text.txt"));
        while(in.hasNextLine()){
            str = str + in.nextLine();
            str.concat("\n");      //Not working!!!!!!!!!!!
        }

        in.close();

        //Writing content to another file
        PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
        out.println(str);
        out.close();
    }
}

3 个答案:

答案 0 :(得分:2)

您在以下行中犯了错误:

str.concat("\n"); 

更新如下:

str = str.concat("\n"); 

我正在提供更新程序。

public class ReadFile {

    public static void main(String[] args) throws IOException {
        try (PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
                Scanner in = new Scanner(new FileReader("text.txt"));) {
            while (in.hasNextLine()) {
                out.println(in.nextLine());
            }
        }
    }
}

答案 1 :(得分:1)

您需要在concat操作后将字符串设置为新值。

str = str.concat("\n"); // or \r\n for Windows.

答案 2 :(得分:-2)

你是串联的字符串,效率不高;使用StringBuilder,也使用独立于平台的行终止符。

请改为尝试:

public class ReadFile {

    public static void main(String[] args) throws IOException {

        String str= "";

        //Reading content from file
        Scanner in = new Scanner(new FileReader("text.txt"));
        StringBuilder str  = new StringBuilder();
        String newLine = System.getProperty("line.separator");
        while(in.hasNextLine()){            
            str.append(in.nextLine()).append(newLine);
        }

        in.close();

        //Writing content to another file
        PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
        out.println(str.toString());
        out.close();
    }
}