Java空输出文件

时间:2017-11-10 13:57:56

标签: java arraylist file-io file-writing storing-data

我正在尝试让程序从输入文件中读取,将数据排序到ArrayList中,然后保存到另一个文件中。 程序运行正常并显示结果,但输出文件显示为空。

public static void main(String[] args) throws IOException {
    String text1 = "";
    try (Scanner input = new Scanner(Paths.get("input.txt"))){
            try (Formatter output = new Formatter("output.txt")){

            List<String> text = new ArrayList<String>();
            while (input.hasNextLine()) {
                text1 = input.next();
                text.add(text1);
            }
            input.close();

            String[] textArray = text.toArray(new String[0]);
            for (String s: textArray) {
                System.out.println(s);
            }

            }
}
}

3 个答案:

答案 0 :(得分:2)

一个问题是使用.next()而不是.nextLine()

try (Scanner input = new Scanner(Paths.get("input.txt"))){
    try (Formatter output = new Formatter("output.txt")){
        while (input.hasNextLine()) {
            String text1 = input.nextLine();
            output.format("%s\r\n", text1);
        }
    }
}

但最好使用Files

Path inputPath = Paths.get("input.txt");
Path outputPath = Paths.get("output.txt");
List<String> lines = Files.readAllLines(inputPath);
lines.sort();
Files.write(outputPath, lines);

答案 1 :(得分:0)

您实际上从未写过文件,只打印println声明中的每一行

尝试添加以下内容:

FileWriter fw = new FileWriter("output.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(s);

答案 2 :(得分:0)

您没有写入文件,因为它已被打开为写入和阅读模式。我已经对您的代码进行了更改,希望它能为您提供帮助

    public static void main(String[] args) throws IOException {
    String text1 = "";
    try (Scanner input = new Scanner(Paths.get("input.txt"))){
            try (Formatter output = new Formatter("output.txt")){

            List<String> text = new ArrayList<String>();
            while (input.hasNextLine()) {
                text1 = input.next();
                text.add(text1);
            }
           input.close();

            String[] textArray = text.toArray(new String[0]);
            for (String s: textArray) {
                output.format("%s",s);
                System.out.println(s);
            }
                 output.close();
            }
      }
}