`

Java读取大文件的处理

 
阅读更多

publicclass ProgressMonitorTest {

publicstaticvoid main(String[] args) {

// 创建一个包含“Click me”的窗口

final JFrame f =new JFrame("ProgressMonitor Sample");

f.getContentPane().setLayout(new FlowLayout());

JButton b = new JButton("Click me");

f.getContentPane().add(b);

f.pack();

 

// 设置按钮的动作事件

b.addActionListener(new ActionListener() {

publicvoid actionPerformed(ActionEvent e) {

// 这儿使用了新的线程处理按钮的动作事件,因为我们需要

// 主窗口的线程响应用户。这样你可以多次点击该按钮,

// 会启动多个读取文件的线程。主窗口也保持响应。

new Thread() {

publicvoid run() {

try {

// 打开文件输出流,把InputStream包装在ProgressMonitorInputStream中。

// 在当前目录中需要放置一个大文件,建议超过50M

String fileName = "D:\\qincidong\\资料\\ext\\深入浅出Ext.JS.徐会生等.pdf";
InputStream in = new FileInputStream(fileName);
ProgressMonitorInputStream pm = new ProgressMonitorInputStream(f, "Reading a big file", in);
ProgressMonitor pmr = pm.getProgressMonitor();
// 读取文件,如果总耗时超过2秒,将会自动弹出一个进度监视窗口。
// 显示已读取的百分比。
int c;
File file = new File(fileName);
long total = file.length();
long curr = 0;
byte[] data = new byte[1024];

while ((c = pm.read(data)) != -1) {
curr += c;
// 处理代码
pmr.setNote("已完成" + (curr*100 / total) + "%");
// 感觉不够明显,这里每执行一次循环,暂停一下
Thread.sleep(1);
}
System.out.println("执行完毕。total:" + total + ",curr:" + curr);
pm.close();

} catch (Exception ex) {

ex.printStackTrace();

}

}

}.start();

}

});

 

// 设置缺省的窗口关闭行为,并显示窗口。

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics