复制图片或者文本另一个文件夹下

标题java日记

day8
在a文件夹下有123.jpg ,copy到b文件夹下
public static void main(String[] args) throws IOException {

File srcFile=new File("D:\\a");//需要复制的文件的源路径
File aimFile=new File("D:\\b");//复制后的文件的目标路径
String srcPath=srcFile.getAbsolutePath();//获得源路径
String aimPath=aimFile.getAbsolutePath();//获得目标路径
//图片过滤器
FilenameFilter filter=new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return (name.endsWith(".jpg")||name.endsWith(".png"));//把以.jpg和.png结尾的文件过滤出来
    }
};
//过滤出的文件
System.out.println(srcPath+"下存在的图片有:");
File[] str=srcFile.listFiles(filter);
for(File i:str){
    System.out.println(i.getName());
}

for(int i=0;i <   str.    length;i++){
    File oldFile=new File(srcPath+"\\"+str[i].getName()); //需要复制的文件
    File newFile=new File(aimPath+"\\"+str[i].getName());//复制后的文件
    //创建流对象
    DataInputStream dis=new DataInputStream(new FileInputStream(oldFile));
    DataOutputStream dos=new DataOutputStream(new FileOutputStream(newFile));

    int temp;
    //读写数据
    while((temp=dis.read())!=-1){//读数据
        dos.write(temp);//把读到的数据写入到Temp文件中
    }

    //关闭流
    dis.close();
    dos.close();
}

System.out.println("文件已复制成功!");

}

在a文件夹下有 三体.txt copy b文件夹下 三体.txt里面的内容大于100字

    public static void main(String[] args)throws Exception{
        File file1 = new File("D:\\a\\三体.txt");
        FileInputStream fis = new FileInputStream(file1);
        File file2 = new File("D:\\b\\santi.txt");
        FileOutputStream fos = new FileOutputStream(file2);
        byte[] buf = new byte[1024];
        int len = -1;
    
        StringBuffer sbuf = new StringBuffer("");
    
        wh

ile ((len = (fis.read(buf))) != -1) {
        sbuf.append(new String(buf, 0, len));
    }

    fos.write(buf);
    }
    先在b文件夹下建一个空白文档,然后运行代码,就能得到。

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值