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("只能上傳文件");
????????????????}
????????????????//如果目標文件是一個已經(jīng)存在的文件夾
????????????????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);
}