1

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");
    }
}
  • http://stackoverflow.com/a/1625263/2947592 – wvdz Nov 13 '13 at 13:32
  • no it's not a duplicate of that question! i am asking someone to debug my program! – user2987896 Nov 13 '13 at 13:35
  • @user2987896 Do not ask for someone to debug your program, we are not your compiler / debugger. For code reviews, there is a separate site for this. Stay nice and show effort, people will help you. Start arguing and things go down the drain from there on. Other than that, welcome at Stack Overflow. – Matthias Nov 13 '13 at 13:39
  • @Matthias sorry! i didn't knew this! could you please tell me the site name? – user2987896 Nov 13 '13 at 13:43
  • @user2987896 Have a look here: http://codereview.stackexchange.com/ I am not active on this site, please make sure to read their about and help page to be sure you are on topic with your questions there. – Matthias Nov 13 '13 at 13:46

2 Answers2

1

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.

Matthias
  • 3,582
  • 2
  • 30
  • 41
0

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");
}
JamesB
  • 7,774
  • 2
  • 22
  • 21