java io如何执行
Java IO 执行方法
Java IO(输入输出)操作主要通过 java.io 包中的类实现,用于处理文件读写、数据流传输等任务。以下是常见的执行方法:
文件读写操作
使用 FileInputStream 和 FileOutputStream 进行文件读写:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileIOExample {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt")) {
int data;
while ((data = fis.read()) != -1) {
fos.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
缓冲流操作
使用 BufferedReader 和 BufferedWriter 提高读写效率:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedIOExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
对象序列化
使用 ObjectOutputStream 和 ObjectInputStream 实现对象序列化和反序列化:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
public class ObjectIOExample {
public static void main(String[] args) {
Person person = new Person("Alice", 30);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
Person deserializedPerson = (Person) ois.readObject();
System.out.println(deserializedPerson);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
字符流操作
使用 InputStreamReader 和 OutputStreamWriter 处理字符流:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class CharacterIOExample {
public static void main(String[] args) {
try (InputStreamReader isr = new InputStreamReader(new FileInputStream("input.txt"), "UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8")) {
int data;
while ((data = isr.read()) != -1) {
osw.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项
- 使用
try-with-resources语句确保资源自动关闭。 - 处理大文件时,优先使用缓冲流以提高性能。
- 序列化对象需实现
Serializable接口。 - 指定字符编码(如 UTF-8)以避免乱码问题。
以上方法涵盖了 Java IO 的基本操作,可根据实际需求选择合适的类和方法组合。






