使用socket上传Java文件,需要上传文件的百分比?

时间:2011-05-19 12:24:12

标签: java android sockets

我正在使用套接字将文件上传到服务器,我需要加载文件的百分比?我该怎么办?我有最大值,即文件长度,我怎样才能获得上传的文件数量? / p>

FileInputStream fis = new FileInputStream(fil);
                BufferedInputStream in = new BufferedInputStream(fis);
                BufferedOutputStream out = new BufferedOutputStream(skt.getOutputStream());

                //Write the file to the server socket           
                int i;

                while ((i = in.read()) != -1) {
                    publishProgress(???);
                    out.write(i);                   
                    System.out.println(i);
                }

我需要在publishProgress方法中传递uploded文件的长度。

4 个答案:

答案 0 :(得分:1)

使用缓冲复制

FileInputStream fis = new FileInputStream(fil);
BufferedInputStream in = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(skt.getOutputStream());

//Write the file to the server socket
int i;
int written = 0;
byte[] buf = new byte[512];

while ((i = in.read(buff)) != -1) {  

    out.write(buff,0,i);
    written += i;
    publishProgress((double)written/length);
    //passing a double value from 0-1 to say how much is transmitted (length is length of file)
    System.out.println(buff+", "+i);
}

答案 1 :(得分:0)

以下是您修改过的代码。 书面保存写入套接字的整数。

FileInputStream fis = new FileInputStream(fil);
BufferedInputStream in = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(skt.getOutputStream());

//Write the file to the server socket           
int i;
int written = 0;

while ((i = in.read()) != -1) {  

    out.write(i);               
    publishProgress(++written);
    System.out.println(i);
}

答案 2 :(得分:0)

要做到这一点,你需要做以下几件事之一:

  1. 使用swfupload等Flash加载程序(请参阅http://demo.swfupload.org/Documentation/),因为这些通常可以访问此类上传进度。
  2. 提供您自己的后台频道:使用Ajax执行表单提交,然后在表单提交时,您运行一个javascript计时器,该计时器点击服务器上的URL,其中包含与上载相对应的某种键。服务器上的URL会查找已上载文件的数量并返回该数字,然后将其传递给uploadProgress方法。

答案 3 :(得分:0)

javax.swing.ProgressMonitorInputStream中