使用套接字上传Java文件,需要上传文件的百分比?

标签 java android sockets

你好,我正在使用套接字将文件上传到服务器,我需要加载文件的百分比?我该怎么做?我有最大值,即文件长度,我如何获得已上传的文件量?

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 方法中传递上传文件的长度。

最佳答案

使用缓冲复制

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

关于使用套接字上传Java文件,需要上传文件的百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6058565/

相关文章:

java - Struts 2 中的全局异常处理程序

java - 是否有可能使 Web 应用程序主动而不是被动?

android - BottomSheetDialogFragment - 允许滚动子项

android - 膨胀类 android.support.v7.widget.RecyclerView(Eclipse) 时出错

python-3.x - 捕获套接字超时错误

java - 使用对象声明数组的数组

javascript - 我可以用 javascript/HTML/CSS 编写一个应用程序并在应用商店、google 的 play 和 microsoft 移动应用商店出售吗?

java - 在同一台机器上调试多个Socket IP地址

c# - 绑定(bind)套接字是否确保其端口始终相同?

Java抽象类通过声明新方法继承