質問

I am making a program that accepts 10 strings and send them to a text file. But, my problem is that it is just overwriting any previous values present in the file. Any ideas how to prevent it overwriting? My program is as follows:

import java.io.*;
public class TEST
{
    public static void main(String args[])throws IOException
    {
        InputStreamReader read=new InputStreamReader(System.in);
        BufferedReader in=new BufferedReader(read);
        int a;
        String x;
        for (a=1; a<=10; a++)
        {
            System.out.println("Please enter a word.");
            x=in.readLine();
            PrintStream konsole = System.out;
            System.setOut(new PrintStream("TEST.txt"));
            System.out.println(x);
            System.setOut(konsole);
        }
        System.out.println("DONE");
    }
}
役に立ちましたか?

解決

Try writing to an output stream (not a redirected System.out).

With FileOutputStreams you can select if you want to append to a file or write a new file (the boolean in the constructor, have a look at the JavaDoc). Try this code to create an output stream to a file which will not overwrite the file, but append to it.

OutputStream out = new FileOutputStream(new File("Test.txt"), true);

Also make sure you do not create the Stream in every iteration of your loop, but at the start of the loop.

If you then also close the output stream after the loop (in a finally block), then you should be ok.

他のヒント

This should work for you:

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

    InputStreamReader read=new InputStreamReader(System.in);
    BufferedReader in=new BufferedReader(read);
    OutputStream out = new FileOutputStream(new File("TEST.txt"), true);

    for (int a=1; a<=10; a++)
    {
        System.out.println("Please enter a word.");
        out.write(in.readLine().getBytes());
        out.write(System.lineSeparator().getBytes());
    }

    out.close();
    System.out.println("DONE");
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top