Java IO流:输入输出的艺术
Java IO流:输入输出的艺术
概述
Java IO流是处理输入输出的机制,它通过流的概念来读写数据。Java提供了丰富的IO类库,包括字节流、字符流、缓冲流等。
1. 字节流
import java.io.*;
// 文件复制
public class FileCopy {
public static void copyFile(String src, String dest) throws IOException {
try (FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
}
}
}
2. 字符流
public class CharStreamDemo {
public static void writeToFile(String filename, String content) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
writer.write(content);
}
}
public static String readFromFile(String filename) throws IOException {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
}
return content.toString();
}
}
3. 缓冲流
public class BufferedStreamDemo {
public static void processLargeFile(String filename) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(filename)))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}
4. 对象序列化
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
private transient String password;
}
public class SerializationDemo {
public static void serialize(Object obj, String filename) throws IOException {
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(filename))) {
oos.writeObject(obj);
}
}
public static Object deserialize(String filename)
throws IOException, ClassNotFoundException {
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(filename))) {
return ois.readObject();
}
}
}
5. File类操作
import java.io.File;
public class FileOperationDemo {
public static void main(String[] args) {
File dir = new File("testDir");
dir.mkdir();
File file = new File(dir, "test.txt");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("文件名: " + file.getName());
System.out.println("绝对路径: " + file.getAbsolutePath());
System.out.println("文件大小: " + file.length() + " bytes");
System.out.println("是否文件: " + file.isFile());
System.out.println("是否目录: " + file.isDirectory());
}
}
6. NIO简介
import java.nio.*;
import java.nio.file.*;
public class NIODemo {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/home/user/file.txt");
System.out.println("文件名: " + path.getFileName());
System.out.println("绝对路径: " + path.toAbsolutePath());
List<String> lines = Files.readAllLines(path);
Files.write(path, lines);
Files.copy(path, Paths.get("/home/user/backup.txt"));
Files.deleteIfExists(path);
}
}
最佳实践
- 使用try-with-resources:自动关闭流资源
- 使用缓冲流:提高IO性能
- 使用NIO:处理大文件和非阻塞IO
- 异常处理:捕获和处理IOException
- 字符编码:指定正确的字符编码
总结
Java IO流是处理输入输出的基础,掌握字节流、字符流、缓冲流和NIO的使用,可以高效地进行文件操作和数据传输。合理选择IO方式,是编写高效Java程序的关键。