zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java复制文件用数据流方法,renameTO()方法是相当于剪切操作

JAVA文件方法 操作 复制 数据流 剪切 相当于
2023-09-14 09:06:40 时间
我想达到的效果是,一个文件复制到另一个地方,然后重命名



//判断是否存在
File file = new File("D:/tomcat9.0.12/apache-tomcat-9.0.12/webapps/paipaixiu_mavenTomcat/upload/app");
//判断是否存在该文件夹,不存在则新建,重启服务器将清空该文件夹里的所有内容
if (!file.exists() || !file.isDirectory()) {
file.mkdirs();
}

// File f = new File("D:/tomcat9.0.12/apache-tomcat-9.0.12/webapps/paipaixiu_mavenTomcat/upload/app/app-release.apk");
// //数据流复制操作,可同时重命名
// copyFileByStream(new File("C:/Users/85339/Desktop/PaiPaixiu/app/release/app-release.apk"), f);
//
// //剪切操作
new File("C:/Users/85339/Desktop/PaiPaixiu/app/release/app-release.apk").renameTo(
new File("D:/tomcat9.0.12/apache-tomcat-9.0.12/webapps/paipaixiu_mavenTomcat/upload/app/派派秀.apk")
);


而使用数据流复制的方法如下:
//拷贝文件
public static void copyFileByStream(File source, File dest) throws IOException {
try (InputStream inputStream = new FileInputStream(source);
OutputStream outputStream = new FileOutputStream(dest)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
}
}


与方法renameTO()的效果不一样,
renameTo的规则是剪切并且可以同时命名,由两种情况无操作,1.原路径的文件找不到,2.目标路径已经有相同名称相同后缀的文件
使用方法:
new File("旧路径").renameTO(new File("新路径"));
如果不重命名则把文件名写一样就可以了