Java 如何从套接字读入数据并将其写入文件?
我试图做的是从套接字连接中读取数据,然后将所有这些数据写入一个文件。我的读者和所有相关声明如下。你知道为什么它不起作用吗?如果你能找到一种更有效的方法来做这件事,那也会很有用 (我的完整代码未成功连接到套接字) 编辑:添加了更多我的代码Java 如何从套接字读入数据并将其写入文件?,java,file,sockets,inputstream,bufferedreader,Java,File,Sockets,Inputstream,Bufferedreader,我试图做的是从套接字连接中读取数据,然后将所有这些数据写入一个文件。我的读者和所有相关声明如下。你知道为什么它不起作用吗?如果你能找到一种更有效的方法来做这件事,那也会很有用 (我的完整代码未成功连接到套接字) 编辑:添加了更多我的代码 public static void main(String args[]) throws IOException { Date d = new Date(); int port = 5195; String filename = ""
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");
}
您的程序要求您为从套接字读取的每一行键入一行。你打字的行数够吗 从控制台读取的行将写入文件,您是否希望套接字中的行写入文件 在哪里关闭文件(和套接字) 另一种方法是使用apacheioutils之类的实用工具
Socket skt = new Socket("localhost", port);
IOUtils.copy(skt.getInputStream(), new FileOutputStream(filename));
skt.close();
我认为这行有一个拼写错误:
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
将“System.in”更改为“in”:
仅供参考,以下是我喜欢阅读套接字的方式。我宁愿避免读卡器提供的字符串编码,而直接使用原始字节:
byte[] buf = new byte[4096];
InputStream in = skt.getInputStream()
FileOutputStream out = new FileOutputStream(filename);
int c;
while ((c = in.read(buf)) >= 0) {
if (c > 0) { out.write(buf, 0, c); }
}
out.flush();
out.close();
in.close();
哦,真可爱,原来代码本质上就是IOUtils.copy()所做的(+1到Peter Lawrey!):
所以我尝试了这个方法,但仍然没有数据写入文件。我正在如下操作端口:
ServerSocketChannel ssc=ServerSocketChannel.open();ssc.socket().bind(新的InetSocketAddress(端口));while(true){System.out.println(“等待连接”);SocketChannel sc=ssc.accept()
看起来不错。如果你通过telnet连接到服务器,你看到你希望接收的数据了吗?skt的作用是什么?连接到你自己?为什么?你为什么不在被接受的SocketChannel上做任何I/O?
byte[] buf = new byte[4096];
InputStream in = skt.getInputStream()
FileOutputStream out = new FileOutputStream(filename);
int c;
while ((c = in.read(buf)) >= 0) {
if (c > 0) { out.write(buf, 0, c); }
}
out.flush();
out.close();
in.close();