Java函数如何实现输入输出流操作?
发布时间:2023-07-06 06:45:28
Java提供了丰富的输入输出流类来实现输入输出操作。这些类主要位于java.io包中,使用它们可以进行文件、网络、控制台等常见数据源的输入输出操作。以下是实现输入输出流操作的常用方法:
1. 使用FileInputStream和FileOutputStream进行文件输入输出操作:
// 从文件读取数据
try (FileInputStream fis = new FileInputStream("input.txt")) {
int data;
while ((data = fis.read()) != -1) {
// 处理读取的数据
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
// 向文件写入数据
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
String data = "Hello, World!";
fos.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
2. 使用BufferedInputStream和BufferedOutputStream进行缓冲输入输出操作:
// 从缓冲输入流读取数据
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt"))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
// 处理读取的数据
System.out.println(new String(buffer, 0, bytesRead));
}
} catch (IOException e) {
e.printStackTrace();
}
// 向缓冲输出流写入数据
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"))) {
String data = "Hello, World!";
bos.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
3. 使用ObjectInputStream和ObjectOutputStream进行对象的序列化和反序列化:
// 对象的序列化
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"))) {
Person person = new Person("John", 25);
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}
// 对象的反序列化
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"))) {
Person person = (Person) ois.readObject();
System.out.println(person.getName() + ", " + person.getAge());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
4. 使用Scanner和PrintWriter进行控制台输入输出:
// 控制台输入
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);
// 控制台输出
try (PrintWriter writer = new PrintWriter(System.out)) {
writer.println("Hello, World!");
} catch (IOException e) {
e.printStackTrace();
}
这些是Java中实现输入输出流操作的一些常用方法,开发者可以根据实际需求选择适合的类和方法来进行操作。
