Basic file byte stream FileInputStream, FileOutputStream

Posted by lhaynes on Sat, 18 Dec 2021 15:45:34 +0100

This paper introduces in detail the methods and usage of the basic file byte stream FileInputStream and FileOutputStream in Java IO.

1 FileInputStream file byte input stream

public abstract class InputStream
extends Object
implements Closeable

This abstract class is a superclass representing all classes of byte input stream. An application that needs to define a subclass of InputStream must always provide a method that returns the next input byte.

public class FileInputStream
extends InputStream

The byte input stream related to the file reads the byte data of the file.

1.1 constructor

public FileInputStream(String name)

When creating an object, specify an abstract path. If the specified file does not exist, or it is a directory rather than a regular file, or cannot be opened for reading for some other reason, FileNotFoundException is thrown.

public FileInputStream(File file)

Create a FileInputStream by opening a connection to the actual file. If the specified file does not exist, or it is a directory rather than a regular file, or cannot be opened for reading for some other reason, FileNotFoundException is thrown.

1.2 API method

public abstract int read()

Read one byte at a time and be able to read English. When reading Chinese, there will be garbled code, because Chinese occupies two bytes and can only read half a Chinese character at a time.

Returns the Unicode value of int type bytes in the range of 0 to 255; If the end of the stream is reached, - 1 is returned.

public int read(byte[] b)

A certain number of bytes are read from the input stream and stored in the buffer array b.

Returns the total number of bytes read into the buffer at one time; If there is no more data available because the end of the stream has been reached, - 1 is returned, that is, the number of bytes read is - 1. The bytes of the buffer will be overwritten one by one by the byte re index 0 read later!

public int available()

Returns the number of bytes remaining (unread) in the file.

public void close()

1.2. 1 supplement

When reading a file using a byte stream:

  1. Using the read () method, you cannot directly read Chinese, because Chinese occupies two bytes, while read reads one byte.
  2. Using the read (byte b []) method, you may not be able to read Chinese (the last index of the array is Chinese).
  3. Using the combination of available and read (byte b []) can read Chinese, but if the file is too large, it may cause memory overflow and program jam. Therefore, it is applicable when you know that the file size will not be very large.

2 FileOutputStream file byte output stream

public abstract class OutputStream
extends Object
implements Closeable, Flushable

The OutputStream abstract class is the base class for all byte output streams.

public class FileOutputStream
extends OutputStream

The byte output stream related to the file outputs byte data to the file.

2.1 constructor

public FileOutputStream(String name)

Creates a file with the specified name and specifies a string Abstract path. If the path file does not exist, create it; If it exists, it is overwritten; If the drive letter of the specified path does not exist or the file is a directory, it will not be created and an exception will be thrown. The following three constructors are the same! It is equivalent to calling FileOutputStream(name,false);

public FileOutputStream(String name,boolean append)

Creates a file with the specified name and specifies a string Abstract path. append: if true, bytes will be written to the end of the file instead of the beginning of the file, that is, write the file instead of overwriting it.

public FileOutputStream(File file)

Creates a File output stream that writes data to the File represented by the specified File object.

public FileOutputStream(File file,boolean append)

Creates a File output stream that writes data to the File represented by the specified File object. If the second parameter is true, bytes are written to the end of the File, not to the beginning of the File. Create a new FileDescriptor object to represent this File connection.

2.2 API method

public void write(int b)

Writes the specified byte to this output stream.

The bytes to be written are the eight low bits of parameter b, and the 24 high bits of b will be ignored. Because the parameter type is int, it is a 32-bit binary number, accounting for 4 bytes, while a byte only needs to occupy 8 bits. To be converted to the corresponding Unicode character output, only the lower 8 bits need to be taken.

public void write(byte[] b)

Writes b.length bytes from the specified byte array to this output stream. Equivalent to calling write(b, 0, b.length)

public void write(byte[] b,int off,int len)

Writes len bytes from the offset off in the specified byte array to this output stream.

Write some bytes in array b to the output stream in order: element b[off] is the first byte written by this operation, and b[off+len-1] is the last byte written by this operation.

public void flush();
public void close();

2.2. 1 supplement

How does the computer recognize when to convert two bytes into a Chinese?

In the computer, the storage of Chinese is divided into two bytes:

The first byte must be negative. The second byte is usually negative and may have a positive number. But it didn't matter. That is, when the computer reads a negative number, it will spell the number and the following number, and then query it in the coding table, which can be converted into Chinese for display.

3 cases

3.1 writing files

public class FileOutputStreamDemo01 {
    
    public static void main(String[] args) throws IOException {
        FileOutputStream fo = new FileOutputStream("C:\\Users\\lx\\Desktop\\test.txt");
        String test = "Aa How do you do";
        byte[] bytes = test.getBytes();
        System.out.println(Arrays.toString(bytes));
        //Write byte
        fo.write(bytes);
        fo.flush();
        fo.close();
    }


    /**
     * Append write
     */
    @Test
    public void test1() throws IOException {
        FileOutputStream fo = new FileOutputStream("C:\\Users\\lx\\Desktop\\test.txt", true);
        String test = "aA How do you do";
        byte[] bytes = test.getBytes();
        for (byte aByte : bytes) {
            fo.write(aByte);
        }
        fo.flush();
        fo.close();
    }

}

3.2 reading files

Byte stream can operate any type of file. If you want to read a file, you only need to read the byte data of the file first, and then convert the byte array into a String string.

public class FileInputStreamdemo01 {
    public static void main(String[] args) throws IOException {
        FileInputStream fi = new FileInputStream("C:\\Users\\lx\\Desktop\\test.txt");
        int i;
   /*while((i=fi.read())!=-1)
   {
       System.out.print((char)i);    //The returned is the ASCII value of a byte character. Printing should be converted to characters, and Chinese cannot be read
   }*/

   /*byte []by=new byte[3];
   while ((i=fi.read(by))!=-1)
   {
       System.out.print(new String(by,0,i));             //Chinese may not be read
   }*/

        //Reading all at once can read Chinese, but if the file is too large, it will cause memory overflow
        byte[] by = new byte[fi.available()];
        while ((i = fi.read(by)) != -1) {
            System.out.print(new String(by, 0, i));
        }
        fi.close();
    }
}

3.3 copying documents

Byte stream can be used to operate any type of file. In addition to text files, the copy here can also copy pictures, videos and other non text files.

public class CopyFile {

    public static void main(String[] args) {
        //Copy picture test
        String str1 = "C:\\Users\\lx\\Desktop\\test.jpg";
        String str2 = "C:\\Users\\lx\\Desktop\\test2.jpg";
        // copy(str1, str2);

        //Copy video test
        String str3 = "C:\\Users\\lx\\Desktop\\test.wmv";
        String str4 = "C:\\Users\\lx\\Desktop\\test2.wmv";
        copy(str3, str4);
    }

    public static void copy(String str1, String str2) {
        FileInputStream fi = null;
        FileOutputStream fo = null;
        try {
            fi = new FileInputStream(str1);
            fo = new FileOutputStream(str2);
            byte[] by = new byte[1024];
            int i;
            while ((i = fi.read(by)) != -1) {
                fo.write(by, 0, i);
                fo.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fi != null) {
                try {
                    fi.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fo != null) {
                try {
                    fo.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

If you need to communicate, or the article is wrong, please leave a message directly. In addition, I hope to like, collect and pay attention. I will constantly update all kinds of Java learning blogs!

Topics: Java io