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