黑马程序员技术交流社区

标题: java程序复制文件的代码里如何实现更改文件后缀名的? [打印本页]

作者: 多一点    时间: 2013-12-24 00:44
标题: java程序复制文件的代码里如何实现更改文件后缀名的?
本帖最后由 多一点 于 2013-12-26 21:54 编辑

public static void main(String[] args) {
                //源文件夹
                String url1 = "D:\\exam\\";
                //目标文件夹
                String url2 = "D:\\exam_copy\\";
                //创建目标文件夹
                (new File(url2)).mkdir();//boolean类型的返回值
                //获取源文件夹下的目录和文件
                 File [] file=(new File(url1)).listFiles();
                 for(int i=0;i<file.length;i++){
                         if(file.isFile()){
                                /* String fileType = file.getName().substring(file.getName().lastIndexOf(".")+1);
                                 System.out.println(fileType);
                                 System.out.println(new File(url2+file.getName()));*/
//这里怎么编写
                                 copy(file,new File(url2+file.getName()));
                         }
                 }
        
        }

        public static void copy(File sourceFile, File newFile) {
                BufferedReader buffr = null;
                BufferedWriter buffw = null;
                try {
                        buffr = new BufferedReader(new FileReader(sourceFile));
                        buffw = new BufferedWriter(new FileWriter(newFile));
                        String line=null;
                        while((line=buffr.readLine())!=null){
                                buffw.write(line);
                                buffw.flush();
                        }
                } catch (IOException e) {
                        throw new RuntimeException("读写文件失败");
                }finally{
                        try {
                                if(buffr!=null)
                                buffr.close();
                        } catch (IOException e) {
                                throw new RuntimeException("读取文件失败");
                        }
                        try {
                                if(buffw!=null)
                                buffw.close();
                        } catch (IOException e) {
                                throw new RuntimeException("写入文件失败");
                        }
                }

        }

}

作者: 刘安成    时间: 2013-12-24 05:00
新建文件时把文件名后缀名写上就行了:new File(url2+“copy.txt”);
作者: 卖火柴    时间: 2013-12-24 08:52
可以自己写路径嘛,比如说File file=new File("F:/a.txt").路径弄对应该就OK.
作者: 多一点    时间: 2013-12-24 16:23
哦 我试试  多谢 解忙
作者: 多一点    时间: 2013-12-24 22:04
已解决````````````````````` 谢谢




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