黑马程序员技术交流社区

标题: 复制一个文件并且修改文件后缀 [打印本页]

作者: tanzhixue    时间: 2015-5-7 18:48
标题: 复制一个文件并且修改文件后缀
本帖最后由 tanzhixue 于 2015-5-23 23:24 编辑

package day0507;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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 Filecopy {
public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
//封装目录的文件
  File sourefile=new File("F:\\BaiduYunDownload\\刘意\\day01\\homework");
//输出到D盘test
  File fileford=new File("D:\\test");
//判断是否存在test这个文件
  if(!fileford.exists()){
//没有就创建
   fileford.mkdir();
  }
//获取指定目录下的所有文件或者文件夹的名称数组
//并且FilenameFilter过滤器把文件夹和不是txt的文件过滤出来
  File[] filearry=sourefile.listFiles(new FilenameFilter() {
   
   @Override

   public boolean accept(File dir, String name) {
    // TODO Auto-generated method stub
    return new File(dir,name).isFile()&&name.endsWith(".txt");
   
   }
  });
//遍历数组
for(File file:filearry)
{
//获取文件名字
  String name=file.getName();
//拼接文件名
  File newfile=new File(fileford,name);
//复制文件方法这里采取缓冲字节流
  copyFile(file,newfile);
  
}
//获取把D盘的test文件数组
File[] desfilearry=fileford.listFiles();
for(File desfile:desfilearry)//遍历
{
// System.out.println(desfile.getName());
  String name=desfile.getName();//获取文件名字
  String newname=name.replace(".txt", ".jpg");//修改后缀
  File newfilel=new File(fileford,newname);//修改之后拼接文件名得到新的文件名字
  desfile.renameTo(newfilel);//把文件名字改写成新的名字
}
}

private static void copyFile(File file, File newfile) throws IOException {
  // TODO Auto-generated method stub
  BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file));
  BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(newfile));
  byte[]bys=new byte[1024];//按字节读取一次1024个
  int len;
//如果-1说明已经读取完毕
  while((len=bis.read(bys)) !=-1){
   bos.write(bys, 0, len);
  }
  bis.close();
  bos.close();
}

}


作者: Richard926    时间: 2015-5-7 19:17
给LZ个建议,最好是养成添加注释的习惯
作者: IDhmpj    时间: 2015-5-7 19:26
Richard926 发表于 2015-5-7 19:17
给LZ个建议,最好是养成添加注释的习惯

最起码应该写个思路在上面,。。。。
作者: 王英明    时间: 2015-5-7 19:26
基础差劲,看读懂!
作者: tanzhixue    时间: 2015-5-23 23:25
已经加上注释了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2