How to write to a file in Java

When writing Java programs, sooner or later there will be a need to read and write information to a file. To do this, the language provides the following tools for inputting and outputting data: Writer class for writing and Reader for reading. The inheritors of these classes are the FileWriter and FileReader classes, convenient for working directly with files.

A simple example of writing to a file in Java

Before creating an entry point into the program, you need to register the imports (the necessary classes are in the java.io * library, we will write an asterisk, because in the future we will need more classes from this library). Import in the editor should look like this:

import java.io.*;

Then, inside the arbitrary class, we write the main method, in which in turn we create an instance of the FileWriter class and write it to the write variable:

FileWriter writer = new FileWriter("text.txt");

When this program starts, the text.txt file will be created in the root of the project. In order to write something to this file, you need to turn to the write () method of the Writer class, the write () method accepts a string as an argument, write something there:

writer.write(" Java");

When working with data output, it is also necessary to take into account exceptional situations due to the fact that we do not always know what will be in this data. The compiler will not skip this code without the special throws Exception construct, which must be inserted in the signature of the main method. You also need to take care of exiting the stream, after the write () method, you need to close the stream using the close () method. What the code should look like at this stage is shown in the figure below.

write to file in java

When the program starts, the text.txt file will appear in the root of the project, in which it will write "an example of writing to a file in Java." However, this example is suitable only for educational purposes, to apply it in a "combat" environment, you need to conduct a little refactoring.

Refactoring

The first thing to do is to enclose the code responsible for entering the output of the data into the try - catch construct (it is easier to manage exceptions and apply your exceptions). Then you need to create a separate variable with the File type, where you can write the address and file name (this is convenient, because you often need to work with several files, they are placed in separate variables and processed in a loop, and only then the resulting variable is inserted as a parameter into FileWriter )

It is also good practice to work with I / O streams using a buffer (the FileWriter class accesses the disk if it can require a lot of data, it is reasonable to manipulate data using a buffer), the BufferedWriter class is used for this, and the FileWriter is written in brackets in as a parameter. To release the buffer, the flush () method is called, it can be written before the close () method, now the code will look like the one shown below.

java write to file line by line

How to write Java to a file line by line

Each time this code is compiled, the same record will be overwritten in the console. How to make new information line by line written when a program starts? To do this, you first need to write the true keyword as the second parameter when creating the FileWriter:

BufferedWriter writer = new BufferedWriter(new FileWriter(myFile, true));

Each time during compilation, the program will write to the file a line that is in the write () method, without transferring to the next line. In our case, it turned out like this:

Java Java Java

A simple way of wrapping a string is to add the / n operator to the string argument of the write () method, but this method will not work on different operating systems. In order to write a file line by line on various platforms, you need to use the line.separator method of the System class. The following example shows how to write this method to the lineSeparator variable, which can then be used in the string argument of the write () method:

String lineSeparator = System.getProperty("line.separator");

The final code will look like the one shown below.

java write to file line by line

The result of the execution of this code will be as follows: in the text.txt file, when the program is run three times, the lines β€œJava sample record” will appear.

Source: https://habr.com/ru/post/K11631/


All Articles