Home > Java > javaTutorial > body text

How Is Text I/O Handled in Java?

WBOY
Release: 2024-07-18 09:44:37
Original
400 people have browsed it

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

The above is the detailed content of How Is Text I/O Handled in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template