Java Advanced Tutorial IO Foundation _java

Source: Internet
Author: User
Tags exception handling readline

The most important function of a computer is to process data. A useful computer language needs to have good IO capabilities to allow the unhandled data to flow into the program and let the processed data flow out.

Java's IO functionality is complex compared to other languages. In other languages, many IO functions, such as reading files, are encapsulated and can be implemented in one or two-line programs. In Java, programmers often need multiple levels of decoration (decoration) in order to achieve file reading.

The advantage of relative complexity is the flexibility of IO. In Java, programmers can control the entire process of IO to design the best IO approach. We will see more in the following sections.

IO Example

Here is the file I used to demonstrate file.txt

Hello world!
Hello nerd!

Let's look at an example of a file read:

Import java.io.*;

public class Test
{public
  static void Main (string[] args)
  {
    try {
      BufferedReader br =
       New BufferedReader (New FileReader ("file.txt")); 

      String line = Br.readline ();

      While [line!= null] {
        System.out.println (line);
        line = Br.readline ();
      }
      Br.close ();
    }
    catch (IOException e) {
      System.out.println ("IO Problem");}}

This program contains a try...catch...finally exception handler. Exception handling can be referenced in the Java Advanced Tutorial

Adorners and functional combinations

The key to program IO is to create BufferedReader object BR:

  BufferedReader br = new BufferedReader (New FileReader ("file.txt"));

In the process of creation, we first set up a FileReader object that is capable of reading a byte stream from the file "file.txt" and converting it to a text stream. In Java, the standard text encoding is Unicode. BufferedReader () receives the FileReader object, expands the FileReader function, and creates a new BufferedReader object. This object provides cache read (buffered) functionality in addition to the ability to read and transform the files above. Finally, by invoking the ReadLine () method on the BR object, we can read the file line by row.

(cache reads are a cache of areas in memory that store FileReader-read text streams.) When the contents of the cache are read (such as the ReadLine () command), the cache loads subsequent text streams. )

BufferedReader () is an adorner (decorator) that receives an original object and returns a decorated, functionally complex object. The advantage of a decorator is that it can be used to decorate different objects. What we are modifying here is the stream of text read from the file. Other text streams, such as standard input, stream traffic, and so on, can be BufferedReader () to enable cache reading.

The following figure shows how BR works, and the data flows from the bottom up:

The above decoration process is similar to the text stream idea in Linux. In Linux, we use similar functions to process and deliver text streams. In Java, we use adorners. But their purpose is similar, is to realize the function of modularity and free combination.

More combinations

In fact, Java provides a rich adorner. The read and convert two steps are merged in the FileReader, and the common default settings are used, such as encoding to take Unicode. We can use the combination of FileInputStream + InputStreamReader to replace the filereader, separating reading bytes and converting two steps, and having better control over two processes.

(Of course, FileReader is more convenient to use.) InputStreamReader is converting FileInputStream to a reader for Unicode text processing

Arrows indicate the direction of data flow

Streaming reads and writes from four base classes: InputStream, OutputStream, reader, and writer. InputStream and reader are processing read operations, OutputStream and writer are processing write operations. They are all located in the Java.io package. The inheritance relationship is as follows:

java.io

In addition, IOException has the following derivative classes:

IOException

Reader and writer and their derived classes are processing Unicode text. As we see buffered Reader, InputStreamReader or FileReader.

InputStream and OutputStream and their derived classes are processing byte (byte) streams. Data in a computer can be considered a byte form, so InputStream and outputstream can be used to handle more extensive data. For example, we can use the following combination to read the data contained in the compressed file (such as integers):

Arrows indicate the direction of data flow

We read the byte stream from the compressed file and then unzip it and read the data.

Write

The write operation is similar to the read operation. We can implement complex writing functions by using decorations. Here is a simple example of writing to text:

Import java.io.*;

public class Test
{public
  static void Main (string[] args)
  {
    try {
      String content = ' Thank you R fish. ";

      File File = new file ("New.txt");

      Create the file if doesn ' t exists
      if (!file.exists ()) {
        file.createnewfile ();
      }

      FileWriter FW = new FileWriter (File.getabsolutefile ());
      BufferedWriter bw = new BufferedWriter (FW);
      Bw.write (content);
      Bw.close ();

    }
    catch (IOException e) {
      System.out.println ("IO Problem");}}

The file object is created above to handle the path.

Summarize

Here is just a basic introduction to Java IO. Java IO is relatively complex. Java programmers need to take some time to familiarize themselves with the classes and their functions in java.io.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.