java如何把一个文件夹内的指定内容转移到另一个文件夹

package IO;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;

public class TransferImage {

	public static void main(String[] args) throws IOException {
		FileInputStream fis;
		FileOutputStream fos;
		//缓存数组
		byte[]bs=new byte[1024*1024*2];
		//从以下路径复制图片
		File allFiles =new File("E:\\素材");
	    //图片过滤器
		FilenameFilter filter=new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String name) {
				// TODO Auto-generated method stub
				return (name.endsWith(".png")||name.endsWith(".jpg"));
			}
		};
		//过滤图片存在str文件数组中
		File []str=allFiles.listFiles(filter);
		//遍历数组
		for(int i=0;i<str.length;i++) {
			//通过循环一个一个获取图片的名字
			String name=str[i].getName();
			//从oldFile取图片
			File oldFile =new File("E:\\素材\\"+name);
			//把图片存入newFile
			File newFile=new File("E:\\File素材\\"+name);
			if (!newFile.exists()) {
				newFile.createNewFile();
			}
			//获取oldFile内的数据
			fis=new FileInputStream(oldFile);
			///存储数据到newFile内(true为可以重复存取)
			fos=new FileOutputStream(newFile,true);
			//存储所有数据
			while(fis.read(bs)!=-1) {
				fos.write(bs);
			}
			//关闭流
			fis.close();
			fos.close();
		}
		//注释部分代码,未添加图片过滤器
//		String []str=allFiles.list();
//		for(String name:str)
//		System.out.println(name);
//		for(int i=0;i<str.length;i++) {
//			String name=str[i];
//			File oldFile =new File("E:\\素材\\"+name);
//			File newFile=new File("E:\\File素材\\"+name);
//			FileInputStream fis=new FileInputStream(oldFile);
//			FileOutputStream fos=new FileOutputStream(newFile);
//			while(fis.read(bs)!=-1) {
//				fos.write(bs);
//			}
//			fis.close();
//			fos.close();
//		}
//		
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_44050588/article/details/88897092