Java中的IO流:如何进行数据读写操作
在Java中,IO(Input/Output)流主要用来处理输入和输出的数据。以下是如何进行基本的读写操作:
文件读写:
FileInputStream
用于读取文件内容。FileOutputStream
用于向文件写入数据。
```java
// 读取文件
FileInputStream fis = new FileInputStream(“example.txt”);
byte[] content = new byte[1024]; // 假设文件不超过1KB
int lengthRead;
while ((lengthRead = fis.read(content))) != -1) {
// 处理读取的内容…
}
fis.close(); // 关闭文件流以释放资源
// 向文件写入数据
FileOutputStream fos = new FileOutputStream(“example.txt”);
String dataToWrite = “Hello, World!”; // 要写入的数据
fos.write(dataToWrite.getBytes()); // 将字符串转换为字节数组再写入
fos.close(); // 关闭文件流以释放资源
```网络读写:
SocketInputStream
和SocketOutputStream
用于处理TCP连接的读写。
```java
// 连接到服务器
Socket socket = new Socket(“localhost”, 1234)); // 假设服务器端口为1234
// 使用SocketInputStream读取数据
InputStream inStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inStream.read(buffer))) != -1) {System.out.println(new String(buffer, 0, bytesRead)))); // 处理读取的数据...
}
// 使用SocketOutputStream向服务器写数据
OutputStream outStream = socket.getOutputStream();
String dataToWrite = “Hello, Server!”; // 要发送的数据
outStream.write(dataToWrite.getBytes())); // 将字符串转换为字节数组再写入// 关闭连接
socket.close(); // 关闭Socket以释放资源
```
以上就是Java中进行基本文件读写以及网络读写的操作。
还没有评论,来说两句吧...