Requirement: Copy picture A from folder A to new file B. If there is no new folder B, create a new one B and change the name of picture A to B. Path:/Users/mgx/apache-tomcat-8.5.78/webapps/img/testimg.jpg
Code:
/**
* 将图片A从文件夹A,复制新文件B并将图片A的名称改为B,
* @param newPath 新文件夹路径
* @param oldPath 图片地址
* @param newFileName 新文件名
* @throws Exception 异常
*/
public static void copyNewFileAndRename(String newPath,String oldPath,String newFileName) throws Exception{
//需要复制到的路径,以及图片的新命名+格式
File result = new File(newPath + newFileName);
//判断该文件夹是否存在,不存在则新增
if (!result.getParentFile().exists()){
result.getParentFile().mkdirs();
}
//需要复制的原图的路径+图片名+ .png(这是该图片的格式)
FileInputStream input = new FileInputStream(oldPath);
FileOutputStream out = new FileOutputStream(result);
//一个容量,相当于打水的桶,可以自定义大小
byte[] buffer = new byte[100];
int hasRead = 0;
while ((hasRead = input.read(buffer)) > 0) {
//0:表示每次从0开始
out.write(buffer, 0, hasRead);
}
System.out.println(result.getAbsolutePath());
input.close();
out.close();
}
public static void main(String[] args) throws Exception {
String oldPath = "/Users/mgx/apache-tomcat-8.5.78/webapps/img/testimg.jpg";
String newPath = "/Users/mgx/apache-tomcat-8.5.78/webapps/img/yuhang/";
String newFileName = "12180606120934678_02.jpg";
FileKit.copyNewFileAndRename(newPath,oldPath,newFileName);
}
After execution:
Path:/Users/mgx/apache-tomcat-8.5.78/webapps/img/yuhang/
Path:/Users/mgx/apache-tomcat-8.5.78/webapps/img/yuhang/12180606120934678_02.jpg