我有一个将一个文件从一个文件夹复制到另一个文件夹的类:
public class Foo extends JFrame{
Timer t;
FileChannel inp = null,
outp= null;
File sourceFile = new File("C:/movies/movie.mkv"),
destFile = new File("C:/test/movie.mkv");
long rec = 0;
long size;
LayoutManager manager = new MigLayout();
public void createUI(){
JPanel panel = new JPanel();
JButton copyFile = new JButton("Copy file");
JButton btn = new JButton("Start function");
JButton stop = new JButton("Stop function");
panel.setLayout(manager);
panel.add(btn);
panel.add(copyFile,"wrap");
panel.add(stop);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setContentPane(panel);
this.setVisible(true);
this.setSize(400,400);
this.pack();
btn.addActionListener((e)->{
try {
inp = new FileInputStream(sourceFile).getChannel();
outp = new FileOutputStream(destFile).getChannel();
size = inp.size();
outp.transferFrom(inp,0,size);
} catch (Exception e2) {
// TODO Auto-generated catch block
System.out.println("FIle not found");
return;
}
t = new Timer(100,i->{
try {
rec = outp.position();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
rec = 0;
}
finally{
System.out.println("Position in file:"+rec);
}
});
t.start();
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(()->new Foo().createUI());
}
}
现在,我有了一个Swing计时器,该计时器每100ms输出一次File中的位置。
我实际上想做的是让用户知道已复制了多少文件。问题是控制台中输出的数字每100毫秒为“文件位置:126089692”。
如果可能的话,我想解释一下。
谢谢你的时间
最佳答案
我在https://docs.oracle.com/javase/8/docs/api/中找到了:
public abstract long transferFrom(ReadableByteChannel src,
long position,
long count)
throws IOException-
“ ...此方法不会修改此频道的位置...”
也许这就是为什么您看到相同的值的原因(我没有检查)。
尝试更换:
rec = outp.position();
通过
rec = inp.position();