在Java中,你可以使用ProgressBar
来显示文件复制的进度。以下是一个简单的示例,展示了如何使用ProgressBar
将文件从一个路径复制到另一个路径:
以下是一个使用Swing ProgressBar
进行文件复制的示例代码:
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class FileCopyWithProgressBar extends JFrame {
private JProgressBar progressBar;
private JLabel statusLabel;
public FileCopyWithProgressBar() {
setTitle("File Copy with Progress Bar");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
statusLabel = new JLabel("Ready");
add(progressBar, BorderLayout.CENTER);
add(statusLabel, BorderLayout.SOUTH);
}
public void copyFile(String sourcePath, String destPath) {
try (InputStream in = new FileInputStream(sourcePath);
OutputStream out = new FileOutputStream(destPath)) {
byte[] buffer = new byte[1024];
int bytesRead;
long totalBytesRead = 0;
long fileSize = new File(sourcePath).length();
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
int progress = (int) ((totalBytesRead / (double) fileSize) * 100);
progressBar.setValue(progress);
statusLabel.setText("Copying... " + progress + "%");
}
statusLabel.setText("Copy complete!");
} catch (IOException e) {
statusLabel.setText("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
FileCopyWithProgressBar frame = new FileCopyWithProgressBar();
frame.setVisible(true);
// Example usage
frame.copyFile("path/to/source/file.txt", "path/to/destination/file.txt");
});
}
}
JProgressBar
组件来显示进度。FileInputStream
和FileOutputStream
来读取和写入文件。通过这种方式,你可以实现一个简单的文件复制进度条,提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云