Java中IO流的使用:文件读写与网络通信
在Java中,IO流主要用于处理文件系统和网络上的数据流动。以下是两部分的主要使用:
- 文件读写
FileInputStream
和FileOutputStream
:用于读取和写入文件内容。
import java.io.*;
public class FileReadWrite {
public static void main(String[] args) {
// 创建一个文件对象
File file = new File("test.txt");
// 如果文件存在,就覆盖其内容
if (file.exists()) {
file.delete();
}
// 使用FileOutputStream写入内容
try (FileOutputStream fos = new FileOutputStream(file)) {
String content = "Hello, World!";
fos.write(content.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
// 读取文件内容
try (FileInputStream fis = new FileInputStream(file)) {
byte[] bytes = new byte[1024]; // 每次读取1KB数据
int count = fis.read(bytes);
if (count != -1) { // 如果成功读取数据,打印出来
String content = new String(bytes, 0, count));
System.out.println(content);
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 网络通信
Socket
和ServerSocket
:用于建立和管理客户端/服务器之间的连接。
import java.io.*;
import java.net.*;
public class NetworkCommunication {
public static void main(String[] args) throws IOException {
// 创建Socket,服务器端等待连接
ServerSocket serverSocket = new ServerSocket(8000);
// 获取Socket对象,客户端向服务器发送请求
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket);
// 客户端向服务器发送消息
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()));
out.writeUTF("Hello, Server!"); // 写入UTF-格式的数据
// 关闭连接
out.close();
clientSocket.close();
serverSocket.close(); // 当所有客户端关闭连接后,关闭服务器端的Socket
}
}
以上就是Java中文件读写和网络通信的基本使用。
还没有评论,来说两句吧...