问题
编写一个程序,将F:\\1目录下面的所有图片[.jpg结尾]复制到F:\\2下面.
有何不同
之前我自己也写过类似的代码,但这次不同的是,代码基本使用了JDK1.8和JDK1.7的API.实现起来逻辑和代码都比之前简单不少.
步骤还是类似:
- 遍历目录,取出文件名;
- 匹配后缀名是否一致;
- 进行复制操作.
代码实现
PS:请使用JDK1.8及以上进行运行.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; /** * 编写一个程序,将F:\\1目录下面的所有图片[.jpg结尾]复制到F:\\2下面. * 并将原来的文件扩展名从.jpg修改为.png * <p> * 例如: * 下面这样的复制. * F:\1\1.jpg----F:\2\1.png * * @author puruidong * @version 2016.2.25 */ public class Main { public static void main(String[] args) { final Path path = Paths.get("F:\\1");//第一个路径,源文件路径 final Path path1 = Paths.get("F:\\2");//第二个,需要复制到的路径 if (!Files.isExecutable(path1)) { System.out.println("需要复制到的文件夹不存在,已自动创建文件夹!"); try { Files.createDirectory(path1); } catch (IOException e) { e.printStackTrace(); } } try { Files .list(path) //取出path下面所有的文件. .filter(file -> file.getFileName().toString().endsWith(".jpg"))// 对后缀进行过滤, // 这里的file.getFileName()返回的是Path对象,必须转换为String之后才能比较 .forEach(x -> { //循环进行处理,在这里看到的数据都是已经过滤过的了. Path filename = x.getFileName();//获得当前文件的名字. String newfilename = filename.toString().replace(".jpg", ".png");//替换名字. String filePath = path + "\" + filename;//当前文件的绝对路径 String saveFilePath = path1 + "\" + newfilename;//需要保存到的新路径(包含文件名) Path tmp = Paths.get(filePath);//两个path对象. Path saveTmp = Paths.get(saveFilePath);//两个path对象. try { Files.copy(tmp, saveTmp, StandardCopyOption.REPLACE_EXISTING);//进行复制操作.第三个参数告诉系统,如果已经存在就进行替换. } catch (IOException e) { e.printStackTrace(); } }); } catch (IOException e) { e.printStackTrace(); } System.out.println("复制完成!"); } } |