This is the 29th day of my participation in the August More Text Challenge

This paper introduces the basic file word stream FileInputStream, FileOutputStream method and usage method in Java IO in detail.

1 FileInputStream Indicates the byte input stream of a file

public abstract class InputStream
extends Object
implements Closeable
Copy the code

This abstract class is a superclass of all classes that represent a byte input stream. Applications that need to subclass InputStream must always provide methods to return the next input byte.

public class FileInputStream
extends InputStream
Copy the code

A file – related byte input stream that reads file byte data.

1.1 the constructor

public FileInputStream(String name)
Copy the code

Creates an object and, when created, specifies an abstract path. A FileNotFoundException is thrown if the specified file does not exist, or if it is a directory rather than a regular file, or if it cannot be opened for reading for some other reason.

public FileInputStream(File file)
Copy the code

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

1.2 API methods

public abstract int read(a)
Copy the code

English can be read one byte at a time. When reading Chinese, garbled characters will appear, because Chinese takes up two bytes and can only read half a character at a time.

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

public int read(byte[] b)
Copy the code

Reads a number of bytes from the input stream and stores them 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, or the number of bytes read is -1. The bytes in the buffer will be overwritten by the byte reindex 0 that is read after!

public int available(a)
Copy the code

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

public void close(a)
Copy the code

1.2.1 adds

When reading a file using a byte stream:

  1. With the read () method, Chinese cannot be read directly because Chinese takes up two bytes, whereas read reads one byte.
  2. Using the read (byte b[]) method, Chinese may not be read (the last index of the array is Chinese).
  3. Using the combination of Available and read (byte b []), Chinese can be read, but if the file is too large, memory may overflow, causing problems such as program lag. Therefore, it is suitable for when you know that the file size will not be large.

2 FileOutputStream Indicates the byte output stream of a file

public abstract class OutputStream
extends Object
implements Closeable.Flushable
Copy the code

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

public class FileOutputStream
extends OutputStream
Copy the code

A file-specific byte output stream that outputs byte data to a file.

2.1 the constructor

public FileOutputStream(String name)
Copy the code

Creates a file with the specified name, specifying a string abstract path. If the path file does not exist, create one. Exist, then cover; If the specified drive does not exist or the file is a directory, an exception is not created and thrown. The same goes for the following three constructors! Equivalent to calling FileOutputStream(name,false);

public FileOutputStream(String name,boolean append)
Copy the code

Creates a file with the specified name, specifying a string abstract path. Append: If true, bytes are written to the end of the file instead of the beginning, that is, appending the file instead of overwriting it.

public FileOutputStream(File file)
Copy the code

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

public FileOutputStream(File file,boolean append)
Copy the code

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

2.2 API methods

public void write(int b)
Copy the code

Writes the specified byte to this output stream.

The bytes to be written are the eight bits of parameter B, and the 24 bits of parameter B are ignored. Since the parameter type is int, it is a 32-bit binary number that takes up 4 bytes, and a byte only takes up 8 bits. To convert to Unicode output, only the low 8 bits are required.

public void write(byte[] b)
Copy the code

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)
Copy the code

Writes len bytes from the specified byte array starting with the offset off to the output stream.

Writes some bytes from array B to the output stream in order: the 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(a);
public void close(a);
Copy the code

2.2.1 supplement

How does a computer know when to convert two bytes into one Chinese?

In computers, Chinese is stored in two bytes:

The first byte is definitely 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 put the number together with the following number, and then query it in the coding table, which can be converted into Chinese 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 = "Hello Aa";
        byte[] bytes = test.getBytes();
        System.out.println(Arrays.toString(bytes));
        / / writing section
        fo.write(bytes);
        fo.flush();
        fo.close();
    }


    /** * appends */
    @Test
    public void test1(a) throws IOException {
        FileOutputStream fo = new FileOutputStream("C:\\Users\\lx\\Desktop\\test.txt".true);
        String test = "Hello aA";
        byte[] bytes = test.getBytes();
        for (byteaByte : bytes) { fo.write(aByte); } fo.flush(); fo.close(); }}Copy the code

3.2 Reading Files

Byte streams can operate on any type of file. To read a file, simply read the file’s byte data and convert the byte array to a 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); // Returns the ASCII value of one byte of characters, which should be converted to characters that cannot read Chinese}*/

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

        // If the file is too large, the memory will overflow.
        byte[] by = new byte[fi.available()];
        while((i = fi.read(by)) ! = -1) {
            System.out.print(new String(by, 0, i)); } fi.close(); }}Copy the code

3.3 Copying Files

Byte streams can be used to manipulate any type of file, in addition to text files, the copy here can also copy images, videos, and other non-text files.

public class CopyFile {

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

        // Copy the 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();
                }
            }
        }
    }
}
Copy the code

If you need to communicate, or the article is wrong, please leave a message directly. In addition, I hope to like, collect, pay attention to, I will continue to update a variety of Java learning blog!