Java使用IO流拷贝文件和拷贝目录
文件的拷贝
import java.io.*;
public class Copy {
public static void main(String[] args) {
boolean isSuccess = copyFile("要复制的文件(全路径或相对路径+文件名)","新的文件名");
if(isSuccess) {
System.out.println("文件复制成功!");
}else {
System.out.println("文件复制失败!");
}
}
private static boolean copyFile(String oldFile, String newFile) {
InputStream is = null;
OutputStream os = null;
StringBuilder builder = new StringBuilder();
try {
is = new FileInputStream(oldFile);
os = new FileOutputStream(newFile);
byte[] flush = new byte[1024];
int len;
while ((len = is.read(flush)) != -1) {
os.write(flush, 0, len);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != os) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (new File(newFile).exists()) {
return true;
}
return false;
}
}
目录的拷贝
import java.io.*;
import java.time.Duration;
import java.time.Instant;
public class CopyDir {
public static void main(String[] args) {
Instant start = Instant.now();
boolean isOk = dirOrFile("要复制的目录路径", "目标路径");
if(isOk){
System.out.println("目录复制完成!");
}else {
System.out.println("目录复制失败!");
}
Instant end = Instant.now();
System.out.println("耗时:"+Duration.between(start,end).toMillis()+"毫秒!");
}
private static boolean copyDir(String oldDir, String newDir) {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(oldDir);
os = new FileOutputStream(newDir);
byte[] flush = new byte[1024];
int len;
while ((len = is.read(flush)) != -1) {
os.write(flush, 0, len);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != os) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
private static boolean dirOrFile(String oldDir, String newDir) {
File old = new File(oldDir);
File copy = new File(newDir);
if (old.isDirectory()) {
copy.mkdir();
File[] files = old.listFiles();
for (int i = 0; i < files.length; i++) {
dirOrFile(files[i].getAbsolutePath(), newDir + "/" + files[i].getName());
}
}
if (old.isFile()) {
copyDir(oldDir, newDir);
}
if (old.length()==copy.length()){
return true;
}
return false;
}
}