【问题标题】:Java filewriter only writing last line to file? [duplicate]Java文件编写器仅将最后一行写入文件? [复制]
【发布时间】:2015-06-08 15:29:34
【问题描述】:

它目前所做的是从文本文件中读取数据并以指定的方式输出它们。当我将它输出到控制台时,它会以所需的方式显示它,但是当我尝试将它输出到文本文件时,由于某种原因它只会写入循环的最后一行。这是我必须处理文件输出的代码:

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

    String gt;
    String gt2;
    int gs1;
    int gs2;
    int total = 0;


    Scanner s = new Scanner(new BufferedReader(
            new FileReader("input.txt"))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");

    while (s.hasNext()) {
        String line = s.nextLine();
        String[] words = line.split("\\s*:\\s*");
        //splits the file at colons

        if(verifyFormat(words)) {
            gt = words[0];       // read the home team
            gt2 = words[1];       // read the away team
            gs1 = Integer.parseInt(words[2]);       //read the home team score
            total = total + gs1;
            gs2 = Integer.parseInt(words[3]);       //read the away team score
            total = total + gs2;
            validresults = validresults + 1;


            File file = new File("out.txt");
            FileOutputStream fos = new FileOutputStream(file);
            PrintStream ps = new PrintStream(fos);
            System.setOut(ps);
            System.out.println(gt + " " +  "[" + gs1 + "]" +  " | " + gt2 + " " + "[" + gs2 + "]");   
            //output the data from the file in the format requested

        }
        else{
            invalidresults = invalidresults + 1;
        }
    }

【问题讨论】:

  • FileOutputStream(等)部分移出循环
  • @Reimeus 在整个街区?
  • 退出 while(s.hasNext()) 循环。所以在扫描仪下方,但在 while 循环上方。

标签: java loops output


【解决方案1】:

每次调用FileOutputStreamPrintStream 的构造函数时,就像重新开始一样。对象不再知道它们应该存储有关循环的先前迭代的信息,因为它们只是被构造的。将所有这些构造函数移出循环并仅调用一次即可解决您的问题。那是

 File file = new File("out.txt");
 FileOutputStream fos = new FileOutputStream(file);
 PrintStream ps = new PrintStream(fos);
 System.setOut(ps);

应该在进入循环之前创建(一次!)while(s.hasNext())

【讨论】:

  • 这已经解决了,我会尽可能选择它作为答案。
  • 很高兴能帮上忙。
【解决方案2】:

每个输入行,您都在创建一个新的输出文件并覆盖旧的。这是因为创建文件的代码在循环里面!

移动这些行:

File file = new File("out.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);

while (s.hasNext()) 行之前

【讨论】:

    猜你喜欢
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2021-03-22
    • 2018-10-06
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多