DEV Community

Cover image for How Is Text I/O Handled in Java?
Paul Ngugi
Paul Ngugi

Posted on

How Is Text I/O Handled in Java?

Text data are read using the Scanner class and written using the PrintWriter class. Recall that a File object encapsulates the properties of a file or a path but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes. The objects contain the methods for reading/writing data from/to a file. For example, to write text to a file named temp.txt, you can create an object using the PrintWriter class as follows:

PrintWriter output = new PrintWriter("temp.txt");

You can now invoke the print method on the object to write a string to the file. For example, the following statement writes Java 101 to the file.

output.print("Java 101");

The next statement closes the file.

output.close();

There are many I/O classes for various purposes. In general, these can be classified as input classes and output classes. An input class contains the methods to read data, and an output class contains the methods to write data. PrintWriter is an example of an output class, and Scanner is an example of an input class. The following code creates an input object for the file temp.txt and reads data from the file.

Scanner input = new Scanner(new File("temp.txt"));
System.out.println(input.nextLine());

If temp.txt contains the text Java 101, input.nextLine() returns the string "Java 101".

Figure below illustrates Java I/O programming. An input object reads a stream of data from a file, and an output object writes a stream of data to a file. An input object is also called an input stream and an output object an output stream.

Image description

Top comments (0)