如何跟踪writeObject()进度

时间:2014-12-13 14:05:29

标签: java tracking progress objectoutputstream

我尝试了以下内容: 但它甚至没有打印出一个数字:/ 文件大小为700mb,需要大约15s

如果我理解正确的话,第二类应该挂钩到输出流 我无法在其他任何地方找到解决方案

问题:我无法跟踪“writeObject()”的过程 - 我正在尝试使用进度条来显示已经上传了多少文件

public class Main {  
      public static void main(String[] args) throws Exception {  


        String file_name = "M:\\Config\\huge.avi";

        File file = new File(file_name);  
        System.out.println(file.getPath());
        if(file.exists()){
            Socket socket = new Socket("localhost", 4112);  


            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());  
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());  

            FileInputStream fis = new FileInputStream(file);  

            MyCountingStream mcs = new MyCountingStream(oos);


            oos.writeObject(file.getName());  

            byte [] buffer = new byte[(int)file.length()];  
            Integer bytesRead = 0;  
            Timeline aftertickz = new Timeline(new KeyFrame(Duration.millis(10), new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent arg0) {
                    System.out.println(mcs.bytesWrittenSoFar());
                }
            }));
            aftertickz.setCycleCount(Timeline.INDEFINITE);
            aftertickz.play();
            while ((bytesRead = fis.read(buffer)) > 0) {
                oos.writeObject(bytesRead);  
                oos.flush();
                oos.writeObject(Arrays.copyOf(buffer, buffer.length));  
            }  

            oos.close();  
            ois.close();  
            mcs.close();
            fis.close();
            socket.close();
            System.exit(0);     
        }else{
            System.out.println("File doesn't exist");
            System.exit(0);
        }
    }  
}  



public class MyCountingStream extends DataOutputStream {
    public MyCountingStream(OutputStream out) {
        super(out);
    }

    public int bytesWrittenSoFar() {
        return written;
    }
}

1 个答案:

答案 0 :(得分:0)

您可以将文件作为原始字节流发送,而不是使用writeObject()然后跟踪(发送的字节数/文件大小,以字节为单位)* 100四舍五入到最接近的整数。

或者..... 看一眼: Getting Progress of ObjectOutputStream/ObjectInputStream