将套接字流写入文件需要很长时间

时间:2018-03-12 13:35:35

标签: java sockets stream

我有一些代码,它将输入流从套接字写入带有缓冲重新读取器的文件。这可行,但由于某种原因,缓冲写入器需要很长时间才能完成对文件的写入(多分钟,其中写入文件的时间少于前2秒)。代码如下:

@Override
    public void handleRequest() {
        Socket s = null;
        BufferedReader br = null;
        Writer writer = null;
        PrintWriter pw = null;

        try {
            s = new Socket(this.getHost(), this.getPort());
            pw = new PrintWriter(s.getOutputStream());
            pw.println(this.getHTTPCommand());
            pw.println(this.getHostCommand());
            pw.print(ENDOFREQUEST);
            pw.flush();
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));

            String currentDir = System.getProperty("user.dir");
            String filePath = this.getPath();
            if(this.getPath().equals("/")){
                filePath = "/index.html";
            }
            Path completePath = Paths.get(currentDir, filePath);
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(completePath.toString()), "utf-8"));
            String t;
            while((t = br.readLine()) != null){
                writer.write(t + "\n");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (writer != null) {
                    writer.close();
                }
                if (br != null) {
                    br.close();
                }
                if (pw != null) {
                    pw.close();
                }
                if (s != null) {
                    s.close();
                }
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

你的while循环后可能需要flush BufferedWriter。它不会影响代码的工作方式,但尝试使用资源也可以整理代码。

相关问题