如何使用IO流移动文件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class Demo6 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入源路径");
String oldP = scanner.nextLine();
System.out.println("请输入目标路径");
String newP = scanner.nextLine();
String regex = "[a-zA-Z]:(((\\\\(?! )[^/:*?<>\\\"\"|\\\\]+)+\\\\?)|(\\\\)?)\\s*";
if (oldP.matches(regex) && newP.matches(regex)) {
File oldPath = new File(oldP);
if (!oldPath.exists()){
System.out.println("源路径不存在");
return;
}else if(oldPath.length()==0){
System.out.println("源路径无内容");
return;
}
File newPath = new File(newP);
if (!newPath.exists()){
newPath.mkdirs();
}
removeFile(oldPath, newPath);
deleteFile(oldPath);
System.out.println("移动成功");
} else {
System.out.println("路径错误,请检查");
}
}
private static void deleteFile(File oldPath) {
if (oldPath.exists()){
File[] files = oldPath.listFiles();
for (File file : files) {
if(file.isFile()){
file.delete();
}else {
deleteFile(file);
}
}
boolean delete = oldPath.delete();
System.out.println(delete);
}
}
private static void removeFile(File oldPath, File newPath) {
if (oldPath.exists()) {
File[] files = oldPath.listFiles();
for (File file : files) {
if (file.isFile()) {
copyFile1(file, newPath);
} else {
File file1 = new File(newPath, file.getName());
file1.mkdirs();
removeFile(file, file1);
}
}
}
}
private static void copyFile1(File file, File newPath) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(file);
fileOutputStream = new FileOutputStream(new File(newPath, file.getName()));
int len = 0;
byte[] bytes = new byte[1024 * 8];
while ((len = fileInputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
fileOutputStream.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fileOutputStream != null)
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}