我正在尝试使用java获取S3的上传百分比进度。我正在尝试这个:
putObjectRequest.setGeneralProgressListener(new ProgressListener() {
@Override
public void progressChanged(ProgressEvent progressEvent) {
progressEvent.getBytesTransferred();
double totalByteRead = 0;
double percentage = 0;
totalByteRead += progressEvent.getBytesTransferred();
percentage += (totalByteRead / size) * 100;
System.out.println("Percentage completed: " + percentage);
if (progressEvent.getEventType() == progressEvent.getEventType()) {
System.out.println("Completed");
}
}
});
s3.putObject(putObjectRequest);
我的输出为:
...
Percentage completed: 2.0119817541351908
Completed
Percentage completed: 1.4128940473756373
Completed
Percentage completed: 0.0
Completed
Percentage completed: 0.0
Completed
如何获得适当的百分比值?
答案 0 :(得分:0)
如果getBytesTransferred()返回非累积值 - 您需要在侦听器方法之外存储总字节数(现在您在侦听器方法中声明变量 totalByteRead ,因此每次重新声明为0 progressChanged 事件被触发)
答案 1 :(得分:0)
// Something to this effect
// percentage += (totalByteRead / size) * 100;
int arraymakerCOUNT=0;
long partial = new Float(size / 100).longValue(); // make 1 percent
long partial2 = partial; // partial and partial2 are 100th of file bytes size
//
long[] percentProgress = new long[100];
while(arraymakerCOUNT < 100){
if(arraymakerCOUNT==0){
percentProgress[arraymakerCOUNT] = partial2;
}else{
partial += partial2; // make partial bigger by 1 percent relating file size count
percentProgress[arraymakerCOUNT] = partial;
}
arraymakerCOUNT++;
} //end while
// Above should be found when the process starts BUT percentProgress[] array should be available in scope to below
// BELOW is for the "change listener" triggered by it or triggers a method with the listener containing its call
int percentCheckLoop = 0; // for the index of the 100 element array containing 1 percent STEP sizes in order
while(percentCheckLoop < 100){ // loop from 1 toward 100 percent by 1 percent at a test
if(percentProgress[percentCheckLoop] < (new Double(totalByteRead).longValue())){
System.out.println("Percentage completed: " + (percentCheckLoop+1);
// switch loop off after printout
percentCheckLoop = 101; // ready the STOP loop condition
}
percentCheckLoop++;
} // end while