gpt4 book ai didi

java - 如何从套接字读取数据并将其写入文件?

转载 作者:行者123 更新时间:2023-11-30 04:59:44 25 4
gpt4 key购买 nike

我想做的是从套接字连接读取数据,然后将所有数据写入文件。我的读者和所有相关陈述如下。有什么想法为什么它不起作用吗?如果您能找到一种更有效的方法来执行此操作,那也会很有用。

(我的完整代码确实成功连接到套接字)

编辑:添加了更多我的代码。

public static void main(String args[]) throws IOException
{

Date d = new Date();
int port = 5195;
String filename = "";
//set up the port the server will listen on
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(port));

while(true)
{

System.out.println("Waiting for connection");
SocketChannel sc = ssc.accept();
try
{

Socket skt = new Socket("localhost", port);
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
FileWriter logfile = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(logfile);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

while ((inputLine = stdIn.readLine()) != null)
{
System.out.println("reading in data");
System.out.println(inputLine);
out.write(inputLine);
System.out.println("echo: " + in.readLine());

}

sc.close();

System.out.println("Connection closed");

}

最佳答案

您的程序要求您为从套接字读取的每一行输入一行。您输入的行数是否足够?

您从控制台读取的行已写入文件,您是否希望将来自套接字的行写入文件?

你在哪里关闭文件(和套接字)

另一种方法是使用 Apache IOUtils 等实用程序

Socket skt = new Socket("localhost", port);
IOUtils.copy(skt.getInputStream(), new FileOutputStream(filename));
skt.close();

关于java - 如何从套接字读取数据并将其写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7246651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com