Reading and writing files in Java

Let’s begin by reading, first we create the file we will use. In fact we will not create the file by Java, we create the object of type File, the file itself must already exist in the specified path.

File readingFile= new File("/home/developer/readingFile.txt");

In my case, I specified the full path of the file because it did not work with the file in the current directory, if you delete the file path, Java will search for the file in the application directory. Then we create the streams for file access.

InputStream reading = new FileInputStream(readingFile);
InputStreamReader rReading = new InputStreamReader(reading );
BufferedReader bReading = new BufferedReader(rReading );

The InputStream class reads bytes from a source, in our case, a. The InputStreamReader class causes the return stream is shaped character, and not in the form of bytes as in InputStream. Finally, the BufferedReader, that reads the text to be faster and more efficient, consuming less memory. Below is an example of what the reading of this file.

String readingText = bReading.readLine();
while(readingText != null){
    System.out.println(readingText );
    readingText = bReading.readLine();
}

The above code needs to be put in a try / catch block because two important exceptions need to be addressed, the FileNotFoundException and IOException, which are respectively the exception for file not found and an error reading stream. After the use of streams, all should be closed with the close() method.

Now writing will not matter if you understand the code above, you will not have difficulties. We will also use three classes, the OutputStream, OutputStreamWriter and BufferedWriter. Below, an example of writing code.

File writingFile = new File("/home/developer/writingFile .txt");
OutputStream writing = new FileOutputStream(writingFile );
OutputStreamWriter wWriting = new OutputStreamWriter(writing );
BufferedWriter bWriting = new BufferedWriter(wWriting );

bWriting.write("This will be the text that will save your file.\n");
bWriting.close();
wWriting.close();
writing .close();

There are other ways to make reading and writing files in Java, I showed what I believe is didactically more interesting by showing better functioning of streams classes. Elsewhere Can I return to the theme and show other ways to work with files.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s