如何将文本文件按每一行发送到客户端
时间: 2023-05-23 22:02:20 浏览: 55
要将文本文件按每一行发送到客户端,可以使用类似以下代码的方法:
```
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server started.");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected.");
InputStream is = clientSocket.getInputStream();
OutputStream os = clientSocket.getOutputStream();
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(os));
String line = null;
while ((line = reader.readLine()) != null) {
writer.println(line);
writer.flush();
}
reader.close();
writer.close();
clientSocket.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这段 Java 代码会在本地 8080 端口启动一个 ServerSocket,等待客户端连接。当客户端连接后,会将文本文件 file.txt 中的每一行发送给客户端,直到所有行都发送完毕。注意,每次发送一行后需要调用 `flush()` 方法来确保数据被发送出去。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)