Java filewriter只写最后一行文件?

时间:2015-06-08 15:29:34

标签: java loops output

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

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

2 个答案:

答案 0 :(得分:4)

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

 File file = new File("out.txt");
 FileOutputStream fos = new FileOutputStream(file);
 PrintStream ps = new PrintStream(fos);
 System.setOut(ps);
在进入循环while(s.hasNext())之前,应该创建

(一次!)。

答案 1 :(得分:1)

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

移动以下行:

An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.dll but was not handled in user code

Additional information: An error occurred while executing the command definition. See the inner exception for details.

Inner Exception: ORA-00932: inconsistent datatypes: expected - got NCLOB

就在.Where(...con1...).Where(...con2...).Where(...etc...)

之前