3

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

4

4 回答 4

3

您可能会发现 ProgressMonitorInputStream 最简单,但如果这对您来说还不够,请查看它的源代码以获得您想要的内容。

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

要使用不同的传输方法,请用适当的流替换 FileInputStream。

于 2009-01-16T17:42:27.190 回答
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;
}

我很确定这会奏效。

于 2009-01-16T22:59:24.023 回答
1

听起来您应该使用SwingWorker.,如本核心 Java 技术提示中所述。另请参阅使用 Swing 工作线程

于 2009-01-15T17:22:41.930 回答
0

那么这里是 JProgressBar 的教程,也许会有所帮助。

于 2009-01-15T16:38:52.813 回答