Java实现文件拷贝,以及修改文件扩展名

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();
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值