java的输入流输出流
时间: 2023-10-17 16:25:49 浏览: 123
Java的输入流和输出流是用来处理数据输入和输出的机制。输入流用于从外部读取数据,而输出流用于向外部写入数据。
Java中的输入流是InputStream类及其子类,主要用于从各种数据源(如文件、网络等)读取数据。常见的输入流有FileInputStream(从文件读取)、ByteArrayInputStream(从字节数组读取)、DataInputStream(从其他输入流中读取基本数据类型)、ObjectInputStream(从输入流中反序列化对象)等。
以下是一个使用FileInputStream读取文件的示例代码:
```java
import java.io.*;
public class ReadFileExample {
public static void main(String[] args) {
try {
// 创建文件输入流
FileInputStream fis = new FileInputStream("test.txt");
// 读取文件内容
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
// 关闭输入流
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
Java中的输出流是OutputStream类及其子类,主要用于将数据写入各种目标(如文件、网络等)。常见的输出流有FileOutputStream(写入文件)、ByteArrayOutputStream(写入字节数组)、DataOutputStream(将基本数据类型写入其他输出流)、ObjectOutputStream(将对象序列化到输出流)等。
以下是一个使用FileOutputStream写入文件的示例代码:
```java
import java.io.*;
public class WriteFileExample {
public static void main(String[] args) {
try {
// 创建文件输出流
FileOutputStream fos = new FileOutputStream("output.txt");
// 写入文件内容
String data = "Hello, World!";
fos.write(data.getBytes());
// 关闭输出流
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上代码只是简单示例,实际应用中通常需要使用try-catch-finally块来确保流的正确关闭。另外,还可以使用BufferedInputStream和BufferedOutputStream等类来提高读写性能。
阅读全文
相关推荐











