-4

I am taking a number of inputs from the user like Name,age,e-mail etc.. , and I concatenated all these fields with a ":" delimiter

`String line = Anjan+":"+21+":"+abc@abcd.com;`

My question is: How do I write the String line into a file? I repeat the process of taking inputs from users. Can somebody explain me, how can I write the line to a file each time, after I am done with reading and concatenating the inputs?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Anjan Baradwaj
  • 1,219
  • 5
  • 27
  • 54
  • 2
    what did you try? edit: http://stackoverflow.com/questions/2885173/java-how-to-create-and-write-to-a-file – Theolodis Sep 11 '13 at 08:35
  • Potentially see http://stackoverflow.com/questions/4614227/how-to-add-a-new-line-of-text-to-an-existing-file-in-java – Alexander Sep 11 '13 at 08:36

3 Answers3

1

If you are using java 7 it will be quite easy,

    public void writerToPath(String content, Path path) throws IOException {
        try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(path,StandardOpenOption.CREATE, StandardOpenOption.APPEND)))){
            writer.newLine();
            writer.write(content);
    }
}

Since Writer implements the AutoClosable interface will the writer and underlying streams be closed when finished or if an exception occur.

Magnus
  • 11
  • 1
0
public static void write(final String content, final String path)
    throws IOException {
    final FileOutputStream fos = new FileOutputStream(path);
    fos.write(content.getBytes());
    fos.close();
}
Luca Mastrostefano
  • 3,201
  • 2
  • 27
  • 34
0

Try the following code. You can create method and pass values as parameter. It'll append the new line every time. It won't remove existing lines(data)

File logFile = new File( System.getProperty("user.home") + File.separator + "test.txt");
String data = "value";
if(!logFile.exists()){
    logFile.createNewFile();
}
FileWriter fstream = new FileWriter(logFile.getAbsolutePath(),true);
BufferedWriter fbw = new BufferedWriter(fstream);
fbw.write(data);
fbw.newLine();
fbw.close();
Vicky Thakor
  • 3,847
  • 7
  • 42
  • 67