Skip to content
Advertisement

Java fileOutputStream

I have been looking around but could not find what I need. I am writing a simple code to save some strings into a .txt file.

I am using:

File archivo = new File(FileName);
fileOutputStream.write(toString().getBytes());
fileOutputStream.flush();

When I do this the .txt is succesfully created and save the info I need to save, BUT it save all in 1 single huge line. How I can save it in diffent lines?

example when I open the txt:

This is line 1This is line 2This is line 3This is line 4

I have add ‘n’ at the end of each string but it doesn’t work.

toString() return a String: “This is line 1”; OS: Windows 7

Advertisement

Answer

You could try doing something like this:

public void write(final File file, final List<String> lines) throws IOException{
    final BufferedWriter writer = new BufferedWriter(new FileWriter(file)); //new FileWriter(file, true) if you want to append the file (default is false)
    for(final String line : lines){
        writer.write(line);
        writer.newLine();
    }
    writer.flush();
    writer.close();
}

If you are using Java 8, feel free to try using lambdas:

public void write(final File file, final List<String> lines) throws IOException{
    final BufferedWriter writer = new BufferedWriter(new FileWriter(file)); //new FileWriter(file, true) if you want to append the file (default is false)
    lines.forEach(
            l -> {
                try{
                    writer.write(l);
                    writer.newLine();
                }catch(IOException ex){
                    ex.printStackTrace();
                }
            }
    );
    writer.flush();
    writer.close();
}

For usage, you could try this:

write(new File(fileName), Arrays.asList("This is line 1", "This is line 2", "This is line 3", "This is line 4"));

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement