如何使用JProgressBar显示文件复制进度?

3

我正在开发一个通过网络传输文件的项目,我想加入一个JProgressBar来显示文件传输过程中的进度,但我需要帮助。


你应该详细说明需要什么帮助。每个文件是否分成数据包,还是只知道何时传输完成?你是否有百分比,只需要帮助显示?你的文件复制程序已经完成了吗? - Andrei Krotkov
社区维基?真的吗? - David Koelle
4个回答

3

你可能会发现ProgressMonitorInputStream最容易使用,但如果这不能满足你的需求,可以查看其源代码,以获取你想要的内容。

 InputStream in = new BufferedInputStream(
                     new ProgressMonitorInputStream(
                              parentComponent,
                              "Reading " + fileName,
                              new FileInputStream(fileName)
                     )
                  );

如果要使用不同的传输方法,可以将适当的流替换为FileInputStream。


1

1
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.JProgressBar;

....

public OutputStream loadFile(URL remoteFile, JProgressBar progress) throws IOException
{
    URLConnection connection = remoteFile.openConnection(); //connect to remote file
    InputStream inputStream = connection.getInputStream(); //get stream to read file

    int length = connection.getContentLength(); //find out how long the file is, any good webserver should provide this info
    int current = 0;

    progress.setMaximum(length); //we're going to get this many bytes
    progress.setValue(0); //we've gotten 0 bytes so far

    ByteArrayOutputStream out = new ByteArrayOutputStream(); //create our output steam to build the file here

    byte[] buffer = new byte[1024];
    int bytesRead = 0;

    while((bytesRead = inputStream.read(buffer)) != -1) //keep filling the buffer until we get to the end of the file 
    {   
        out.write(buffer, current, bytesRead); //write the buffer to the file offset = current, length = bytesRead
        current += bytesRead; //we've progressed a little so update current
        progress.setValue(current); //tell progress how far we are
    }
    inputStream.close(); //close our stream

    return out;
}

我相信这个会起作用。


我建议您查看Java NIO通道以复制文件。 - Frederic Morin
请注意,FYI out.write(buffer, current, bytesRead) 应更改为 out.write(buffer, 0, bytesRead)。 - Ed Griffin

0

这里有一个关于JProgressBar的教程,或许可以帮到你。点击这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接