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

时间:2011-08-30 16:35:48

标签: java file sockets inputstream bufferedreader

我要做的是从套接字连接中读取数据,然后将所有内容写入文件。我的读者和所有相关陈述如下。任何想法为什么它不起作用?如果你能看到更有效的方法来做到这一点也很有用。

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

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

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");

        }

2 个答案:

答案 0 :(得分:2)

您的程序要求您为从套接字读取的每一行键入一行。你打的行足够吗?

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

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

另一种方法是使用像Apache IOUtils

这样的实用程序
Socket skt = new Socket("localhost", port);
IOUtils.copy(skt.getInputStream(), new FileOutputStream(filename));
skt.close();

答案 1 :(得分:0)

我认为这一行有一个错字:

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

将“System.in”更改为“in”:

BufferedReader stdIn = new BufferedReader(new InputStreamReader(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()所做的(给Peter Lawrey +1):

http://svn.apache.org/viewvc/commons/proper/io/trunk/src/main/java/org/apache/commons/io/CopyUtils.java?view=markup#l193