Java函数的输入和输出流的处理方法
Java 提供了多种处理输入和输出流的方法,下面将分别介绍输入流和输出流的处理方法。
一、输入流的处理方法
输入流用于从外部读取数据到程序中,Java 中常用的输入流有 InputStream 及其子类,例如 FileInputStream、BufferedInputStream 等。
1. 文件输入流
文件输入流用于读取文件中的数据,常用的方法有 read()、read(byte[] b) 和 read(byte[] b, int off, int len)。例如:
try (FileInputStream fis = new FileInputStream("input.txt")) {
int data = fis.read(); // 读取一个字节数据
byte[] buffer = new byte[1024];
int len = fis.read(buffer); // 读取多个字节数据到缓冲区
len = fis.read(buffer, 0, 1024); // 从偏移量为 0 的位置读取 len 个字节数据到缓冲区
} catch (IOException e) {
e.printStackTrace();
}
2. 缓冲输入流
缓冲输入流包装了其他输入流,以提供缓冲的功能,常用的方法有 read()、read(byte[] b) 和 read(byte[] b, int off, int len)。例如:
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt"))) {
int data = bis.read(); // 读取一个字节数据
byte[] buffer = new byte[1024];
int len = bis.read(buffer); // 读取多个字节数据到缓冲区
len = bis.read(buffer, 0, 1024); // 从偏移量为 0 的位置读取 len 个字节数据到缓冲区
} catch (IOException e) {
e.printStackTrace();
}
3. 标准输入流
标准输入流 System.in 是一个 InputStream,用于从控制台读取数据,可以使用 Scanner 或 BufferedReader 来处理标准输入流。例如:
try (Scanner scanner = new Scanner(System.in)) {
String input = scanner.nextLine(); // 读取一行输入字符串
int num = scanner.nextInt(); // 读取一个整数
} catch (Exception e) {
e.printStackTrace();
}
二、输出流的处理方法
输出流用于向外部写入数据,Java 中常用的输出流有 OutputStream 及其子类,例如 FileOutputStream、BufferedOutputStream 等。
1. 文件输出流
文件输出流用于向文件中写入数据,常用的方法有 write(int b)、write(byte[] b) 和 write(byte[] b, int off, int len)。例如:
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
fos.write(97); // 写入一个字节数据
byte[] buffer = {'H', 'e', 'l', 'l', 'o'};
fos.write(buffer); // 写入多个字节数据
fos.write(buffer, 0, 5); // 从偏移量为 0 的位置写入 5 个字节数据
} catch (IOException e) {
e.printStackTrace();
}
2. 缓冲输出流
缓冲输出流包装了其他输出流,以提供缓冲的功能,常用的方法有 write(int c)、write(byte[] b) 和 write(byte[] b, int off, int len)。例如:
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"))) {
bos.write(97); // 写入一个字节数据
byte[] buffer = {'H', 'e', 'l', 'l', 'o'};
bos.write(buffer); // 写入多个字节数据
bos.write(buffer, 0, 5); // 从偏移量为 0 的位置写入 5 个字节数据
} catch (IOException e) {
e.printStackTrace();
}
3. 标准输出流
标准输出流 System.out 是一个 PrintStream,用于向控制台输出数据,可以使用 System.out.println() 或 System.out.print() 来处理标准输出流。例如:
System.out.println("Hello, World!"); // 输出一行字符串
System.out.print(123); // 输出一个整数
以上是 Java 函数的输入和输出流的处理方法,通过使用不同的输入流和输出流,可以实现数据的读取和写入操作。根据具体的需求和场景,选择合适的输入流和输出流来处理数据。
