Java实现文件拷贝,以及修改文件扩展名
方法一:单纯实现文件拷贝
public File createNewFile(String path, String realPath, String newFileName) {
File file = new File(path); // path原文件路径,被复制的文件
File dir = new File(realPath); // realPath复制的目标路径
if (!dir.exists()) { // 判断路径是否存在
dir.mkdirs();
}
File newFile = new File(realPath, newFileName); // 创建新文件对象
try {
newFile.createNewFile(); // 创建新文件
fileChannelCopy(file, newFile); // 复制模板到新文件
} catch (Exception e) {
e.printStackTrace();
}
return newFile;
}
public void fileChannelCopy(File s, File t) { // 以流的方式读取、写入文件
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(s), 1024);
out = new BufferedOutputStream(new FileOutputStream(t), 1024);
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
2、方法二:实现文件拷贝并修改文件扩展名
此方法需要下载commons-io-2.6.jar
import org.apache.commons.io.FileUtils;
public void CopyAndRenamePictures(String airpath){ //实现功能:在路径下,拷贝png图片,并重命名图片为jpg
try {
File file = new File(airpath);
//获取路径下的文件列表
String[] list = file.list();
if(null!=list && list.length>0){
//遍历文件列表
for(String pngFilename : list){
//将文件转化为File对象
File oldFile = new File(airpath, pngFilename);
if(!oldFile.isDirectory()){
//如果文件名中包含png,则替换为jpg
if(pngFilename.contains(".png")){
String jpgFilename = pngFilename.substring(0, pngFilename.lastIndexOf(".")) + ".jpg";
//为新的jpg文件,在原来目录中创建File对象
File newFile = new File(airpath, jpgFilename);
//使用copyFile方法把复制旧文件至新文件
FileUtils.copyFile(oldFile, newFile);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}