为什么我的文本文件在每次执行后都不会被覆盖?

时间:2014-04-22 20:14:35

标签: java

我的程序读入文本文件in.txt。该文本文件可以具有任意数量的行。

我的问题是,当我尝试写入输出(out.txt)文件时,它会附加它而不是覆盖。

输出文件应与输入文件具有相同的编号。

    try {
        inFile = new Scanner(new File("in.txt"));

        while (inFile.hasNext()) {

        // Methods and stuff that doesn't matter...
        // Problem starts here

            try{
                outFile = new PrintWriter((new FileWriter("out.txt", true)));
                outFile.println(ArrayToString(intArray));                   
            }
            catch (IOException e) {
                System.out.print("Could not find and write to the output file. " + e);
                e.printStackTrace();
            }
            finally {
                outFile.flush();
                outFile.close();
            }
        }
    }
    catch (FileNotFoundException e) {
        System.out.print("Could not find the input file. " + e);
        e.printStackTrace();
    }

ArrayToString方法返回要写入的字符串。

编辑:

我忘了添加这个细节:

再次阅读说明后,我不应该创建一个文本文件,只是检查它是否在那里。

3 个答案:

答案 0 :(得分:3)

请参阅the Javadoc for the FileWriter constructor

  

public FileWriter(String fileName,             布尔附加)              抛出IOException

     

在给定带有布尔值的文件名的情况下构造FileWriter对象   指示是否附加所写的数据。

尝试将append标志设置为false。然后使用相同的编写器而不是每次通过循环创建一个新的编写器(意味着你应该在while循环的开头上面声明FileWriter)。

(顺便说一下,请查看java.util.Arrays.toString,您不需要为此编写自己的代码。)

答案 1 :(得分:2)

问题在于:

        try{
            outFile = new PrintWriter((new FileWriter("out.txt", true)));
            outFile.println(ArrayToString(intArray));                   
        }
        catch (IOException e) {
            System.out.print("Could not find and write to the output file. " + e);
            e.printStackTrace();
        }

将PrintWriter行更改为:

       outFile = new PrintWriter((new FileWriter("out.txt", false)));

现在,看起来你正在通过输入文件的每个循环打开文件。如果您想要打开此文件一次,并为输入文件中的每一行写入,请在while循环外移动打开和关闭,如下所示:

    try {

    inFile = new Scanner(new File("in.txt"));
    // here we open the out file, once
    outFile = new PrintWriter((new FileWriter("out.txt", false)));

    while (inFile.hasNext()) {

    // Methods and stuff that doesn't matter...
    // Problem starts here

        try{
            // this will write a line to the out.txt file containing the intArray as a String
            outFile.println(ArrayToString(intArray));                  
        }
        catch (IOException e) {
            System.out.print("Could not find and write to the output file. " + e);
            e.printStackTrace();
        }

    }
}
catch (FileNotFoundException e) {
    System.out.print("Could not find the input file. " + e);
    e.printStackTrace();
}
finally {
            inFile.close();
            outFile.flush();
            outFile.close();
        }

答案 2 :(得分:0)

变化

outFile = new PrintWriter((new FileWriter("out.txt", true)));

outFile = new PrintWriter((new FileWriter("out.txt", false)));

outFile.println(ArrayToString(intArray));

outFile.print(ArrayToString(intArray));