java新手写的选择器复制文件

本文介绍了一个使用Java缓存流进行文件复制的示例程序。通过选择源文件及目标目录,程序能够实现不同类型文件(如.txt, .avi, .mp3等)的快速复制,并显示复制所耗时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package fileCopyAndShearDemo;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;


import javax.swing.JFileChooser;


public class BufferedStreamCopyDemo {
static final String pathName = "D:/";
public static void main(String[] args) {
long time = Copy();
System.out.println("复制共耗时:" + (time / 1000) + "秒!" + "总共为:" + time + "毫秒!");


}
/**复制文件---使用缓存流*/
public static long Copy() {
File file = new File(pathName);
String pathName2;
InputStream inputStream = null;
OutputStream outputStream = null;
BufferedInputStream binputStream = null;
BufferedOutputStream boutputStream = null;
JFileChooser jfilechoose = new JFileChooser(file);
jfilechoose.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
jfilechoose.showOpenDialog(null); //打开文件选择器
file = jfilechoose.getSelectedFile();
JFileChooser Jfilechooser2 = new JFileChooser(new File("D:/"));
Jfilechooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
Jfilechooser2.showOpenDialog(null);
pathName2 = Jfilechooser2.getSelectedFile().getAbsolutePath();
String Name = Jfilechooser2.getName(file);


System.out.println("file:" + Name);
String[] suffix = {".txt",".avi",".mp3"};
int Index = -1;
for (int i = 0; i < suffix.length; i++) {
if(Name.endsWith(suffix[i])) {
Index = i;
break;
}
}
if(Index == -1) {
System.out.println("暂时不支持该后缀!");
System.out.println("Program exit!");
System.exit(0);
}
pathName2 += "\\oneCopy2" + suffix[Index];
System.out.println("复制路径为:" + pathName2);
File file2 = new File(pathName2);
if(file == null) {
System.out.println("No Select!");
System.out.println("Program exit!");
System.exit(0);
}
long startTime = System.currentTimeMillis();
try {
inputStream = new FileInputStream(file);
binputStream = new BufferedInputStream(inputStream);
outputStream = new FileOutputStream(file2);
boutputStream = new BufferedOutputStream(outputStream);
System.out.println("正在复制,请稍后.......");
int i = -1;
while((i = binputStream.read()) != -1) {
boutputStream.write(i);
}
System.out.println("复制成功!");



} catch (Exception e) {
e.printStackTrace();
}finally {
try {
boutputStream.close();
outputStream.close();
binputStream.close();
inputStream.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
long endTime = System.currentTimeMillis();
return (endTime - startTime);
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值