overview
Java I/O operations refer to data input/output operations.
Java's I/O operation classes are in the java.io package, mainly divided into the following categories:
- I/O interface based on byte operation: InputStream and OutputStream
- I/O interface based on character operation: Writer and Reader
- I/O interface based on disk operation: File
1. Introduction to Core Classes
- Byte-based I/O operations, the core is to operate the byte array byte[], which can operate any type of stream data
- Character-based I/O operations, the core is to operate the character array char[], and can only operate character-type stream data. If it is non-character stream data (such as pictures, videos, etc.), it will become garbled
1. Byte input stream
kind | Function | illustrate |
---|---|---|
ByteArrayInputStream | Use the memory buffer as an InputStream | Connect it to the FilterInputStream object to store the byte stream in the file |
FileInputStream | read information from a file | Convert the file object File into an input stream to read the data in the file |
FilterInputStream | An abstract class that acts as a decorator interface that provides useful functionality to other InputStream classes | |
BufferedInputStream | Provides buffer operations to improve IO performance; add buffering function for incoming input streams | FilterInputStream subclass |
DataInputStream | Used in conjunction with DataOutputStream to read basic data types from streams in a ported manner; includes all interfaces for reading basic data types | FilterInputStream subclass |
2. Byte output stream
kind | Function | illustrate |
---|---|---|
ByteArrayOutputStream | Create a buffer in memory. All data sent to the stream is placed in this buffer | It is convenient to convert the input stream into a byte array |
FileOutputStream | for writing information to a file | |
FilterOutputStream | Abstract class, interface that acts as a decorator, providing useful functionality for other OutputStreams | |
BufferedOutputStream | Provides buffer operations to improve IO performance; add buffering function to the incoming output stream, you can call flush() to clear the buffer | FilterOutputStream subclass |
DataOutputStream | Used in conjunction with DataInputStream, basic data types can be written to the stream in a transplanted manner; it includes all interfaces for writing basic data types | FilterOutputStream subclass |
3. Character input stream
kind | Function | illustrate |
---|---|---|
InputStreamReader | Convert byte input stream InputStream to character input stream | |
FileReader | Converts the file object File to a character input stream | Subclass of InputStreamReader |
BufferedReader | Provide buffer function to improve the operation performance of character input stream Reader | |
StringReader | Convert a string to a character stream operation |
4. Character output stream
kind | Function | illustrate |
---|---|---|
OutputStreamWriter | Convert byte output stream OutputStream to character output stream | |
FileWriter | Converts the file object File to a character output stream | Subclass of OutputStreamWriter |
BufferedWriter | Provide buffer function to improve the operation performance of character output stream Writer | |
StringWriter | Convert a string to a character stream operation |
2. Introduction to key operations
1. Close the stream
All data streams need to call the close method to close after the operation is completed. It is recommended to use the statement to use the stream in 1.7 and later, try-with-resources
so as to avoid calling the close() method explicitly, reduce some repetitive code, and automatically call close after the operation is completed. method.
try-with-resources
The statement can automatically close all java.io.Closeable
subclass objects that implement the interface.
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
bos.write(content.getBytes());
bos.flush();
}
2. Refresh the cache
The flush() method is used to force the OutputStream object to write the data temporarily stored in the internal buffer immediately (in general, it is not necessary to call this method manually, after the internal buffer is filled, it will automatically execute the actual The write operation will also automatically call the flush() method when calling the close() method)
3. Serialization stream and deserialization stream
The serialization of an object is to convert the object into a byte sequence, and vice versa is called deserialization, ObjectOutputStream is a serialization stream, and ObjectInputStream is a deserialization stream.
The object to be operated must implement the serialization interface Serializable. If you do not want a certain field to be serialized, you can use transient to modify the field so that the field will not be serialized, or you can manually serialize it by rewriting and methods writeObjectOverride()
.readObjectOverride()
Static variables cannot be serialized either, because all objects share the same static variable value
1) ObjectOutputStream serialization stream
The main method is writeObject, which stores the class of the object, the signature of the class, and the values of all non-static and non-transient fields in this class and its parent classes
public final void writeObject(Object obj) throws IOException {
if (enableOverride) {
writeObjectOverride(obj);
return;
}
try {
writeObject0(obj, false);
} catch (IOException ex) {
if (depth == 0) {
writeFatalException(ex);
}
throw ex;
}
}
2) ObjectInputStream deserialization stream
The main method is readObject, which reads back the class of the object, the signature of the class, and the values of all non-static and non-transient fields in this class and its superclasses
public final Object readObject()
throws IOException, ClassNotFoundException
{
if (enableOverride) {
return readObjectOverride();
}
// if nested read, passHandle contains handle of enclosing object
int outerHandle = passHandle;
try {
Object obj = readObject0(false);
handles.markDependency(outerHandle, passHandle);
ClassNotFoundException ex = handles.lookupException(passHandle);
if (ex != null) {
throw ex;
}
if (depth == 0) {
vlist.doCallbacks();
}
return obj;
} finally {
passHandle = outerHandle;
if (closed && depth == 0) {
clear();
}
}
}
3. Code example
import org.springframework.util.StopWatch;
import java.io.*;
public class FileUtilTest {
/**
* 复制文件
*/
public static void copyFile(String fromFileName, String toFileName) throws Exception {
File fromFile = new File(fromFileName);
File toFile = new File(toFileName);
StopWatch watch = new StopWatch("fileTest");
watch.start("copy");
if (!fromFile.exists()) {
System.out.println("源文件不存在");
System.exit(1);
}
if (!toFile.getParentFile().exists()) {
toFile.getParentFile().mkdirs();
}
try (InputStream is = new FileInputStream(fromFile);
OutputStream os = new FileOutputStream(toFile)) {
int temp = 0;
byte[] data = new byte[4096];
while ((temp = is.read(data)) != -1) {
os.write(data, 0, temp);
}
watch.stop();
System.out.println(watch.prettyPrint());
}
}
/**
* 通过字符流将字符串写入到文件中
*/
public static void write(String fileName, String content) throws IOException {
File file = new File(fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try (Writer out = new FileWriter(file)) {
out.write(content);
out.flush();
}
}
/**
* 通过字节流将字符串写入到文件中,增加缓冲区功能
*/
public static void writeBuffer(String fileName, String content) throws IOException {
File file = new File(fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
bos.write(content.getBytes());
bos.flush();
}
}
/**
* 通过字符流将字符串写入到文件中,增加缓冲区功能
*/
public static void writeBufferedWriter(String fileName, String content) {
File file = new File(fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
bw.write(content);
bw.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通过字符流,从文件中读取字符串内容
*/
public static void readChar(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
return;
}
try (Reader in = new FileReader(file)) {
char[] data = new char[4096];
int len;
StringBuilder sb = new StringBuilder();
while ((len = in.read(data)) != -1) {
sb.append(new String(data, 0, len));
}
in.close();
System.out.println(sb);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通过字节流,从文件中读取字符串内容
*/
public static void readByte(String fileName) throws IOException {
File file = new File(fileName);
if (!file.exists()) {
return;
}
try (InputStream in = new FileInputStream(file)) {
byte[] data = new byte[4096];
int len;
StringBuilder sb = new StringBuilder();
while ((len = in.read(data)) != -1) {
sb.append(new String(data, 0, len));
}
System.out.println(sb);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通过字符流,从文件中读取字符串内容,增加缓冲区功能
*/
public static void readBufferReader(String fileName) throws Exception {
File file = new File(fileName);
if (!file.exists()) {
return;
}
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
}
}
/**
* 通过字节流,从文件中读取字符串内容,增加缓冲区功能
*/
public static void readBuffer(String fileName) throws Exception {
File file = new File(fileName);
if (!file.exists()) {
return;
}
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
int len;
byte[] data = new byte[4096];
while ((len = bis.read(data)) != -1) {
System.out.println(new String(data, 0, len));
}
}
}
/**
* 将文件内容转换成字节数组
*/
public static byte[] file2OutStream(String fileName) throws Exception {
File file = new File(fileName);
if (!file.exists()) {
return null;
}
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
int len;
byte[] data = new byte[4096];
while ((len = bis.read(data)) != -1) {
bos.write(data, 0, len);
}
return bos.toByteArray();
}
}
/**
* 将Java对象序列化存储在到文件中
*/
public static void objWrite(String fileName) {
File file = new File(fileName);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
oos.writeObject("Hello ,World");
oos.writeBoolean(false);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从序列化文件中反序列化出Java对象
*/
public static void objRead(String fileName) {
File file = new File(fileName);
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
Object o = ois.readObject();
System.out.println(o.getClass());
System.out.println("o = " + o);
System.out.println("ois.readBoolean() = " + ois.readBoolean());
} catch (Exception e) {
e.printStackTrace();
}
}
}