拷贝文件(java)
srcPath(源地址) desPath(目标地址)
1、普通拷贝(地址的形式)
public static void testOnCopyFile(String srcPath,String desPath){
File srcFile = new File(srcPath);
File desFile = new File(desPath);
try {
InputStream is = new FileInputStream(srcFile);
OutputStream os = new FileOutputStream(desFile);
byte[] data = new byte[1024];
int len = 0;
while((len = is.read(data))!= -1){
os.write(data, 0, len);
}
os.flush();
os.close();
is.close();
} catch (Exception e) {
System.out.println("读取失败");
}
}
2、以文件形式拷贝
//通过文件形式拷贝
public static void testOnCopyFile(File src,File des) throws IOException{
if(! src.isFile()){
System.out.println("只能上传文件");
throw new IOException("只能上传文件");
}
//如果目标文件是一个已经存在的文件夹
if(des.isDirectory()){
System.out.println("只能拷贝文件");
throw new IOException("不能建立同名的文件夹");
}
try {
InputStream is = new FileInputStream(src);
OutputStream os = new FileOutputStream(des);
byte[] data = new byte[1024];
int len = 0;
while((len = is.read(data))!= -1){
os.write(data, 0, len);
}
os.flush();
os.close();
is.close();
} catch (Exception e) {
System.out.println("读取失败");
}
}
3、测试文件
@Test
public void test1(){
String srcPath = "D:/KFO/parent/1122.txt";
String desPath = "D:/KFO/parent/test1/2233445566.txt";
testOnCopyFile(srcPath, desPath);
}
@Test
public void test2() throws IOException{
File srcFile = new File("D:/KFO/parent/1122.txt");
File desFile = new File("D:/KFO/parent/test1/22334455.txt");
testOnCopyFile(srcFile, desFile);
}