There is the following piece of code:

OutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } try { assert outputStream != null; assert text != null; outputStream.write(text.getBytes()); } catch (IOException e) { e.printStackTrace(); } 

The problem is that after the execution, the contents of the file are deleted, and text.getBytes() is output to the console.

How can I fix it?

    1 answer 1

    To create an object of class FileOutputStream you use the constructor:

     FileOutputStream(String name) 

    When using this constructor, the data will be written to the beginning of the file, therefore when writing information to the file, everything that was in it before will be deleted.

    To write data to the end of the file, use the constructor:

     FileOutputStream(String name, boolean append) 

    with append flag true .


    The void write(byte[] b) FileOutputStream class does not write data to the file itself, but to the stream buffer (in order not to touch the file on the disk again and write in larger blocks). To write information to a file, after calling the write(...) method, you must either:

    • call the flush() method, if you continue to work with the stream,

    or

    • call the close() method, if you don’t work with this stream.

    In the above code snippet, nothing can be displayed on the console, except for stack-traces.

    • Added a call to the close() method, what is needed is actually written to the file, but the problem with the output to the console remains:! The output of the program - Evgeniy
    • @Evgeniy, On which line is the console output? - post_zeew
    • @zeew, Began to look for the string, I realized that I was calling a method in which there is output of this array. I apologize for the carelessness. - Evgeniy