本例以Windows, JDK1.7 为基础,来演示对文件的移动。
使用两种方式来对文件进行移动:
1.通过调用调用File.renameTo()的方法
2.通过拷贝文件,完成拷贝之后删除源文件
详细的代码如下:
FileMove.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| package com.devnp.io;
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
public class FileMove {
public static void main(String[] args) { rename(); }
public static void rename(){ File file = new File("D:\\Person-Test\\1.txt"); File newfile = new File("D:\\Person-Test\\1_new.txt"); if(file.renameTo(newfile)){ System.out.println("File Rename succesful."); } }
public static void copy(){ InputStream inStream = null; OutputStream outStream = null;
try{
File afile =new File("D:\\Person-Test\\1.txt"); File bfile =new File("D:\\Person-Test\\2.txt");
inStream = new FileInputStream(afile); outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length; while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close(); outStream.close();
System.out.println("File is copied successful!"); afile.delete();
}catch(IOException e){ e.printStackTrace(); } }
}
|
Author:
Darren Du
License:
Copyright (c) 2019 MIT LICENSE