IO streams,

1. Input stream

Byte input stream

FileInputSteam

1. Construction method:

public FileInputStream(File file) {}

public FileInputStream(FileDescriptor fdObj){}

public FileInputStream(String name){}

Copy the code

2, read method:

// Read one byte at a time

public int read(a){}



// Read b.length bytes into the byte array

public int read(byte b[]){}



Read len bytes from the input stream into the byte array

public int read(byte b[], int off, int len){}

Copy the code

3. File reading:

1, the read ()

Returns the number of bytes read one at a time, or -1 if the end of the file is reached.

The text

abc

Copy the code


public static void method_01(String filePath) throws IOException {

  FileInputStream inputStream = null;

  try {

    inputStream = new FileInputStream(filePath);

  // Read one byte at a time

    for (int i = 0; i < 4; i++) {

      int read = inputStream.read();

      System.out.println(read);

    }

  } catch (FileNotFoundException e) {

    e.printStackTrace();

  } finally {

    if (null! = inputStream) {

      // Close the IO stream

      inputStream.close();

    }

  }

}

Copy the code

Execution Result:

97

98

99

-1

Copy the code

The result shows that the first three times read data, return the corresponding ASCII code, when the end of the file read, return -1.


2, read (byte [] b)

The total number of bytes read into the buffer, or -1 if the end of the file is reached.

Text:

abcdefg

Copy the code

Declare a byte array larger than the real data to read the data.

public static void method_02(String filePath) throws IOException {



  FileInputStream inputStream = null;

  try {

    inputStream = new FileInputStream(filePath);



    // The declared length is greater than the actual data length

    byte[] bytes = new byte[20];



    int length = inputStream.read(bytes);



    System.out.println("Byte array length :" + bytes.length + "Length of bytes read :" + length);



    for (byte b : bytes) {

      System.out.print(b + "|");

    }

  } catch (FileNotFoundException e) {

    e.printStackTrace();

  } finally {

    if (null! = inputStream) {

      inputStream.close();

    }

  }

}

Copy the code

Execution Result:

Byte array length:20Length of data read:7

97 | 98 | 99 | 100 | 101 | 102 | 103 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 

Copy the code

It can be seen that when the length of the byte array is greater than the real length of an array of bytes, so do vacate the space behind the all use 0, it also reflects the another problem, we in the use of byte [] array read a file, don’t say I set the length of the large enough, you can rest easy reading efficiency, if there are any small files, It is also easy to cause inefficiency.


3, read(byte b[], int off, int len)

The total number of bytes read into the buffer, or -1 if read to the end of the file;

Text:

abcdefg

Copy the code

Declare a fixed – size array of bytes that loop through the data

Our text is seven bytes long, declares a two-length array, and should loop four times, returning -1 on the fifth read.

public static void method_03(String filePath) throws IOException {



  FileInputStream inputStream = null;

  try {

    inputStream = new FileInputStream(filePath);



    // Declare two lengths

    byte[] bytes = new byte[2];



    int i = 0;

    while (i < 5) {

      int length = inputStream.read(bytes, 0, bytes.length);

      System.out.println("The first" + (i + 1) + "Time read, length:" + length);

      System.out.println("Start output :");

      for (int j = 0; j < length; j++) {

        System.out.print(bytes[j] + "|");

      }

      System.out.println();

      i++;

    }

  } catch (FileNotFoundException e) {

    e.printStackTrace();

  } finally {

    if (null! = inputStream) {

      inputStream.close();

    }

  }

}

Copy the code

Execution Result:

The first1Times read, length:2

Start output:

97 | 98 | 

The first2Times read, length:2

Start output:

99 | 100 | 

The first3Times read, length:2

Start output:

101 | 102 | 

The first4Times read, length:1

Start output:

103 | 

The first5Second read, length: -1

Start output:

Copy the code

Note:

Some friends may encounter the problem I met before, for they wrote Chinese characters or punctuation marks in their text, “garbled characters will appear”, we add a Chinese character to the text at the end, and convert the byte array we read into String for output, and see what happens.

public static void method_03(String filePath) throws IOException {

  FileInputStream inputStream = null;

  try {

    inputStream = new FileInputStream(filePath);



    byte[] bytes = new byte[2];



    int i = 0;

    while (i < 5) {

      inputStream.read(bytes, 0, bytes.length);

      

      // Convert byte[] to string

      String s = new String(bytes, StandardCharsets.UTF_8);

      System.out.println(s);

      i++;

    }

  } catch (FileNotFoundException e) {

    e.printStackTrace();

  } finally {

    if (null! = inputStream) {

      inputStream.close();

    }

  }

}

Copy the code

Results:

ab

cd

ef

G �

� �

Copy the code

At the beginning of my brain, I felt that this is what problem, how can garbled code, if a little bit of attention will find that Chinese accounts for 3 byte bytes, you use 2 to store that definitely garbled code ah. So you must have thought that maybe I should have made the array declaration a little bit bigger, because if you’ve thought that, then you probably don’t know how nasty society is.

So what to do? Is there really nothing that can be done? Let’s use an example to learn how to solve this problem.

A 🌰 :

Read out the contents of the text and print it to the console.

Since we know that the above garbled code is caused by the difference in the number of bytes taken up by English and Chinese, if we know the length of bytes taken up by the entire file, then we can not read out at once. As it happens, FileInputStream provides such a method (available) that we can get the number of bytes occupied by the entire file.

public static void printConsole(String filePath) throws IOException {



  FileInputStream inputStream = null;

  try {

    inputStream = new FileInputStream(filePath);



    // Get the total number of bytes for the entire text

    int available = inputStream.available();



    // Declare an array

    byte[] bytes = new byte[available];



    // Read data

    int readLength = inputStream.read(bytes, 0, available);

    String s = new String(bytes, StandardCharsets.UTF_8);



    System.out.println("Read length :" + readLength + " available:" + available);

    System.out.println("Read content:" + s);

  } catch (FileNotFoundException e) {

    e.printStackTrace();

  } finally {

    if (null! = inputStream) {

      inputStream.close();

    }

  }

}

Copy the code

Results:

Length read:30  available:30

Abcdef The growth of a programmer

Copy the code

In this case, we can read the entire text. Only with this in mind can we understand why our write file downloads are judged by the number of bytes read! =-1, otherwise it’s really hard to remember.


Character input stream

FileReader

1. Construction method:

public FileReader(String fileName){};



public FileReader(File file){};



public FileReader(FileDescriptor fd){};

Copy the code

2, read method:

public int read(a){};



public int read(char cbuf[], int offset, int length){};



public int read(char cbuf[]){};

Copy the code

3. File reading:

FileReader’s read method reads a single character (char), so when mixing English and Chinese, we don’t have to use different bytes to cause garbled characters.

Text:

Abcdef the growth of a programmer

Copy the code

The code to read the content:

public static void method_01(String filePath) throws IOException {



  FileReader fr = null;

  try {

    fr = new FileReader(filePath);



    int c;

    // Read one character at a time. If the value is -1, the file is read to the end

    while((c = fr.read()) ! = -1) {

      System.out.println((char) c);

    }

  } catch (FileNotFoundException e) {

    e.printStackTrace();

  } finally {

    if (null! = fr) {

      fr.close();

    }

  }

Copy the code

Results:

a

b

c

d

e

f

one

a

cheng

sequence

member

the

into

long

Copy the code

Read () reads a single character each time, so the other two read methods are the same as byte stream reads.

For more information, please follow our wechat official account: