gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:40:27 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com