Table of contents
Java byte stream (Byte Stream)
FileInputStream和FileOutputStream
Java character stream (Character Stream)
How to distinguish when to use output and when to use input
What is the exception thrown by the close method itself in Java
FileOutputStream (file output stream)
FileInputStream (file input stream)
A stream in Java is a way of data transfer that can pass input or output data from one place to another. Java's I/O library provides two types of streams: byte streams and character streams.
Java byte stream (Byte Stream)
Java byte stream reads and writes in bytes and is the recommended way to handle all types of binary data. They are most widely used in I/O infrastructure because they deal with raw binary data.
FileInputStream和FileOutputStream
The most basic byte stream classes in Java are FileInputStream and FileOutputStream. The file input stream (FileInputStream) is used to read data from the file, and the file output stream (FileOutputStream) is used to write data to the file. These two classes can be used to move binary data, such as images and sounds.
-
advantage
- Byte streams can be used with any type of file, including text and binary.
- Byte streams are generally faster than character streams and perform better when processing large amounts of data.
-
shortcoming
- Not suitable for handling text data and may cause encoding problems.
- Manual encoding and decoding is required when processing text files.
-
Use Cases
- Image and video read and write operations
- Data Compression and Encryption
Java character stream (Character Stream)
The Java character stream reads and writes in units of characters and is the preferred way to process text data. They are encoded using Unicode and represented in memory using a 16-bit character set.
FileReader and FileWriter
The most basic character stream classes in Java are FileReader and FileWriter. The file reader (FileReader) is used to read data from the text file, and the file writer (FileWriter) is used to write data to the text file.
-
advantage
- Character streams are often more convenient than byte streams when dealing with text files.
- Automatic codec, without manual conversion.
-
shortcoming
- Not as efficient as byte streams when dealing with binary data.
- Not all types of files, such as pictures or videos, can be processed.
-
Use Cases
- Read and write operations on text files
- Read and write operations of text data in network transmission
In general, byte streams are suitable for processing any type of file, but manual encoding and decoding is required when processing text data. Character streams are suitable for processing text files and are automatically encoded and decoded. Therefore, it is very important to select the appropriate stream according to specific usage scenarios and requirements.
How to distinguish when to use output and when to use input
This problem has troubled me for a long time, and it will be confused at critical moments. For this reason, I wrote the following: (Take the file read and write stream as an example)
FileInputStream: file input stream, read data from the file, method read();
FileOutputStream: file output stream, write data to the file, method write();
Remember the above two sentences, don't ask why, just remember, and ask why when you have completely remembered;
Write method
Why is this method taken out separately here? Because this method itself throws a checked exception , you must handle it before compiling;
In Java, write()
methods are used to write data to an output stream. The method itself may throw a variety of exceptions, including the following:
-
IOException
- Description: Thrown when an I/O error occurs, such as a file system error or network error.
-
NullPointerException
- Description: Thrown when the parameter is null.
-
IndexOutOfBoundsException
- Description: Thrown when the specified offset and length exceed the range of valid data.
BufferedOutputStream
It is important to note that calling write()
a method does not necessarily trigger an I/O operation if you are using a buffered stream object (for example ). Instead, it will store the data in a buffer and only perform actual I/O operations when the buffer is full or if the buffer is manually flushed. In this case, if an I/O error occurs, the exception may be thrown when the buffer is flushed, rather than when the write()
method is called.
close method
In order to deepen the associative memory, we are taking out the close method separately, and it will also throw an exception . I always thought that his exception was just a null exception (that is, when the value of the stream object is null, the exception is still thrown when close is called. ), but it is not the case. Take the following code as an example (note that there are errors in the following code):
if(fin!=null){
fin.close();
}
Because I will report an exception when I write fin.close() alone, so I added an if judgment outside fin.close(), and then it will still throw an exception. After that, I found something wrong, and checked the information again:
What is the exception thrown by the close method itself in Java
In Java, close()
a method is a method used to close a stream. When a method is called close()
, an exception may occur and be thrown . Specifically, close()
methods themselves may throw IOException
exceptions.
IOException
Is a checked exception (checked exception) in Java, indicating that a general error has occurred during the input/output process. Because close()
the method involves I/O operations, it may throw IOException
an exception in the process of closing the stream. For example, when using file I/O streams, IOException
an exception may occur if the read/write operation has not completed before closing the stream. Likewise, when using network sockets, if an error occurs while reading or writing data to or from the socket, IOException
an exception may occur before the socket is closed.
Therefore, when using close()
methods, you need to use try-catch statements to catch exceptions that may be thrown IOException
and perform appropriate exception handling. close()
In general, it is good programming practice to call methods in a finally block to ensure that resources are released properly. For example:
FileInputStream in = null;
try {
in = new FileInputStream("example.txt");
// ...
} catch (IOException e) {
// 处理异常
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// 处理异常
}
}
}
FileOutputStream (file output stream)
Then let's talk about FileOutputStream, this stream object is awesome, and there are some unknown operations:
In Java, FileOutputStream
there are two constructors to create a file output stream object. The parameters of these two constructors are as follows:
-
FileOutputStream(File file)
- Parameter Type:
File
- Description: Creates a file output stream object that writes data to the specified file. If the specified file does not exist, an attempt will be made to create it.
- Parameter Type:
-
FileOutputStream(String name, boolean append)
- Parameter Type:
String name
: The filename (including its path).boolean append
: If true, this file output stream will be opened for append writing; otherwise the file will be overwritten.
- Description: Creates a file output stream object that writes data to the specified file. If the specified file does not exist, and
append
the argument is false, an attempt will be made to create the file.
- Parameter Type:
It should be noted that if you use the second constructor to create FileOutputStream
an object, you can also use another overloaded constructor to set the buffer size. For example:
FileOutputStream fos = new FileOutputStream("example.txt", true);
BufferedOutputStream bos = new BufferedOutputStream(fos, 4096);
In the above code, BufferedOutputStream
the constructor function of takes an FileOutputStream
object and an integer parameter as input. This integer represents the size of the buffer. Output performance can be improved and system calls reduced by using the constructor with a buffer size parameter
FileInputStream (file input stream)
Compared with the output stream, the input stream is relatively simple: In Java, FileInputStream
there are three constructors used to create a file input stream object. The parameters of these three constructors are as follows:
-
FileInputStream(File file)
- Parameter Type:
File
- Description: Create a file input stream object that reads data from the specified file .
- Parameter Type:
-
FileInputStream(String name)
- Parameter Type:
String
- Description: Creates a file input stream object that reads data from the specified pathname (including the filename) .
- Parameter Type:
-
FileInputStream(FileDescriptor fdObj)
- Parameter Type:
FileDescriptor
- Description: Create a file input stream object that reads data from the specified file descriptor .
- Parameter Type:
Note that FileInputStream
the class does not have a constructor that sets up the buffer. If you need to use an input stream object with a buffer, you can use it FileInputStream
with BufferedInputStream
. For example:
FileInputStream fis = new FileInputStream("example.txt");
BufferedInputStream bis = new BufferedInputStream(fis, 4096);
In the above code, BufferedInputStream
the constructor takes an FileInputStream
object and an integer parameter as input. This integer represents the size of the buffer. Input performance can be improved and the number of system calls reduced by using the constructor with a buffer size parameter.
FileInputStream file input stream, when the file in the parameter does not exist, an exception will be thrown directly and no attempt will be made to create a new file;
In Java, FileInputStream
the constructor is used to create an input stream object that reads data from a file. If the specified file does not exist, FileNotFoundException
an exception is thrown instead of attempting to create the file.
Therefore, if you want to use FileInputStream
read data from a file, and you are not sure whether the file exists, you can avoid the exception by following these steps:
- Use classes in Java
File
or other file manipulation APIs to check if the file exists. - If the file exists, use
FileInputStream
the constructor to create the input stream object; otherwise, perform appropriate error handling.
For example, the following code demonstrates how to check for the existence of a file and use FileInputStream
read data from the file:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamExample {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
// 从输入流中读取数据...
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.err.println("File not found: " + file.getAbsolutePath());
}
}
}
In the above code, first check whether the file exists, and if so, use FileInputStream
the constructor to create an input stream object and read data from it. If the file does not exist, output an error message and terminate the program.
It should be noted that FileInputStream
it can only be used to read existing files and cannot be used to create new files. If you need to create a new file, you should use FileOutputStream
(or other file manipulation API) to create an output stream and write the data.
read method and Write method
In this part, we mainly emphasize the parameters and return values of the read and write methods , as you can see from the figure below,
-
return value :
int
: Returns the number of bytes actually read. Returns -1 if the end of the file has been reached. In practical applications, we use the returned value to judge whether the data has been read;
- parameter
- An empty parameter means that one byte of data is read at a time, and then there are others;
For the Write method, he has no return value, mainly parameters, which can write one byte at a time, or the data of a byte array;
fou = new FileOutputStream("./2.txt");
fin = new FileInputStream("");
String str = new String("qwertyuiop");
fou.write(2);//write方法本身会抛出异常;一次写入一个字节
fou.write(str.getBytes());//一次写入一个字节数组