Java的IO学习目录
文章目录
一、Java IO 基础概念
1. IO 流的概念与分类
- 输入流 vs 输出流
- 输入流(
InputStream
/Reader
):从数据源读取数据(如文件、网络) - 输出流(
OutputStream
/Writer
):向目标写入数据(如文件、控制台)
- 输入流(
- 字节流 vs 字符流
- 字节流(
InputStream
/OutputStream
):处理二进制数据(图片、音频等) - 字符流(
Reader
/Writer
):处理文本数据(.txt
,.csv
等)
- 字节流(
- 节点流 vs 处理流
- 节点流(
FileInputStream
,FileReader
):直接操作数据源 - 处理流(
BufferedInputStream
,BufferedReader
):包装节点流,提供额外功能(缓冲、转换等)
- 节点流(
二、字节流操作
1. 文件字节流
import java.io.*;
public class FileByteStreamExample {
public static void main(String[] args) {
String filePath = "test.txt";
// 写入文件
try (FileOutputStream fos = new FileOutputStream(filePath)) {
fos.write("Hello, Java IO!".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
// 读取文件
try (FileInputStream fis = new FileInputStream(filePath)) {
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 缓冲字节流(提高性能)
import java.io.*;
public class BufferedByteStreamExample {
public static void main(String[] args) {
String filePath = "test.txt";
// 写入(缓冲)
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath))) {
bos.write("Buffered IO is faster!".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
// 读取(缓冲)
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath))) {
int data;
while ((data = bis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. 数据字节流(读写基本数据类型)
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) {
String filePath = "data.dat";
// 写入 int, double, boolean
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(filePath))) {
dos.writeInt(100);
dos.writeDouble(3.14);
dos.writeBoolean(true);
} catch (IOException e) {
e.printStackTrace();
}
// 读取
try (DataInputStream dis = new DataInputStream(new FileInputStream(filePath))) {
System.out.println(dis.readInt()); // 100
System.out.println(dis.readDouble()); // 3.14
System.out.println(dis.readBoolean()); // true
} catch (IOException e) {
e.printStackTrace();
}
}
}
三、字符流操作
1. 文件字符流
import java.io.*;
public class FileCharStreamExample {
public static void main(String[] args) {
String filePath = "text.txt";
// 写入(字符流)
try (FileWriter fw = new FileWriter(filePath)) {
fw.write("Hello, 字符流!");
} catch (IOException e) {
e.printStackTrace();
}
// 读取(字符流)
try (FileReader fr = new FileReader(filePath)) {
int data;
while ((data = fr.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 缓冲字符流(逐行读取)
import java.io.*;
public class BufferedCharStreamExample {
public static void main(String[] args) {
String filePath = "text.txt";
// 写入(缓冲)
try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) {
bw.write("第一行");
bw.newLine();
bw.write("第二行");
} catch (IOException e) {
e.printStackTrace();
}
// 读取(逐行)
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. 转换流(处理编码问题)
import java.io.*;
public class ConvertStreamExample {
public static void main(String[] args) {
String filePath = "text_gbk.txt";
String charset = "GBK"; // 处理中文编码问题
// 写入(GBK 编码)
try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charset)) {
osw.write("中文测试");
} catch (IOException e) {
e.printStackTrace();
}
// 读取(GBK 解码)
try (InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), charset)) {
int data;
while ((data = isr.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
四、标准 IO 与重定向
1. 标准输入输出流
import java.util.Scanner;
public class StandardIOExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入内容:");
String input = scanner.nextLine();
System.out.println("你输入的是:" + input);
}
}
2. 重定向(System.setOut)
import java.io.*;
public class RedirectExample {
public static void main(String[] args) throws FileNotFoundException {
// 把 System.out 重定向到文件
PrintStream fileOut = new PrintStream("output.txt");
System.setOut(fileOut);
System.out.println("这行内容会被写入文件,而不是控制台!");
}
}
五、文件与目录操作
1. File 类(文件/目录操作)
import java.io.File;
public class FileOperationExample {
public static void main(String[] args) {
File file = new File("test.txt");
// 检查文件是否存在
System.out.println("文件是否存在?" + file.exists());
// 创建文件
try {
if (!file.exists()) {
file.createNewFile();
System.out.println("文件已创建!");
}
} catch (IOException e) {
e.printStackTrace();
}
// 删除文件
if (file.delete()) {
System.out.println("文件已删除!");
}
}
}
2. 文件过滤器
import java.io.File;
import java.io.FilenameFilter;
public class FileFilterExample {
public static void main(String[] args) {
File dir = new File(".");
// 只列出 .txt 文件
String[] txtFiles = dir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
});
for (String file : txtFiles) {
System.out.println(file);
}
}
}
六、对象序列化
1. 基本序列化
import java.io.*;
class Person implements Serializable {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class SerializationExample {
public static void main(String[] args) {
Person person = new Person("张三", 25);
String filePath = "person.dat";
// 序列化(写入对象)
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化(读取对象)
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) {
Person loadedPerson = (Person) ois.readObject();
System.out.println(loadedPerson.name + ", " + loadedPerson.age);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
七、NIO 基础
1. Files 和 Path(Java NIO 2)
import java.nio.file.*;
import java.util.List;
public class NIOExample {
public static void main(String[] args) throws IOException {
Path path = Paths.get("test.txt");
// 写入文件
Files.write(path, "Hello, NIO!".getBytes());
// 读取文件
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
}
}
八、IO 最佳实践
1. try-with-resources(自动关闭流)
import java.io.*;
public class TryWithResourcesExample {
public static void main(String[] args) {
// Java 7+ 自动关闭流
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 大文件处理(避免内存溢出)
import java.io.*;
public class LargeFileExample {
public static void main(String[] args) {
String inputFile = "large_file.txt";
String outputFile = "output.txt";
try (BufferedReader br = new BufferedReader(new FileReader(inputFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
九、高级主题
1. 压缩流(Zip 文件处理)
import java.io.*;
import java.util.zip.*;
public class ZipExample {
public static void main(String[] args) throws IOException {
// 压缩文件
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("archive.zip"))) {
zos.putNextEntry(new ZipEntry("file1.txt"));
zos.write("Hello, Zip!".getBytes());
zos.closeEntry();
}
// 解压文件
try (ZipInputStream zis = new ZipInputStream(new FileInputStream("archive.zip"))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
System.out.println("文件名: " + entry.getName());
int data;
while ((data = zis.read()) != -1) {
System.out.print((char) data);
}
}
}
}
}
十、实战项目
1. 文件加密/解密工具(XOR 简单加密)
import java.io.*;
public class FileEncryptor {
public static void encryptFile(String inputFile, String outputFile, int key) throws IOException {
try (FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile)) {
int data;
while ((data = fis.read()) != -1) {
fos.write(data ^ key); // XOR 加密
}
}
}
public static void main(String[] args) throws IOException {
encryptFile("plain.txt", "encrypted.dat", 123);
encryptFile("encrypted.dat", "decrypted.txt", 123); // 解密
}
}
总结
- 字节流:
InputStream
/OutputStream
(二进制数据) - 字符流:
Reader
/Writer
(文本数据) - 缓冲流:
BufferedInputStream
/BufferedReader
(提高性能) - 对象序列化:
ObjectInputStream
/ObjectOutputStream
- NIO:
Files
、Path
(更高效的文件操作) - 最佳实践:
try-with-resources
、大文件处理
这个目录涵盖了 Java IO 的核心知识点,并提供了完整的代码示例,适合从入门到进阶学习! 🚀