在我们开发中经常会遇到文件复制操作,基于代码可读性原则,再次推荐一个类库的操作方法,具体代码如下:
package 设计模式.Single_Thread_Execution.源码底层;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author Heian
* @time 19/02/02 22:19
* @copyright(C) 2019 深圳市北辰德科技股份有限公司
* 用途:文件复制
*/
public class CopyFileDemo {
public static void copyFile(){
OutputStream out = null;
InputStream in = null;
try {
out = new FileOutputStream (new File ("D://b.log"));
in = new FileInputStream ("D://a.log");
int len = 0;
byte[] bytes = new byte[1024];
while ((len=in.read (bytes)) != -1){
out.write (bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
if (out != null ){
try {
out.close ();
} catch (IOException e) {
e.printStackTrace ();
}
}
if (in != null){
try {
in.close ();
} catch (IOException e) {
e.printStackTrace ();
}
}
}
}
//底层和上述代码类似
public static void copyFileNew(){
Path path = Paths.get ("D://a.log");//源文件
try {
Files.copy (path,new FileOutputStream (new File ("D://b.log")));
} catch (IOException e) {
e.printStackTrace ();
}
}
public static void main(String[] args) {
//CopyFileDemo.copyFile ();
CopyFileDemo.copyFileNew ();
}
}