- /**
- * 编写程序,将指定目录下所有.java文件拷贝到另一个目的中,并将扩展名改为.txt
- *
- * @author zyy
- *
- */
- public class Test9 {
- public static void main(String[] args) {
- copy(new File("D:\\WorkSpace\\java\\exam\\src\\com\\itheima"),
- new File("D:\\demo"));
- }
- /**
- * 文件所有拷贝
- *
- * @param source
- * 数据源
- * @param target
- * 目标源
- */
- private static void copy(File source, File target) {
- if (!source.exists()) {
- throw new RuntimeException("source file is not exit");
- }
- // 判断文件夹是否存在
- if (!target.exists()) {
- target.mkdirs();// 创建多及目录
- }
- File[] file = source.listFiles();
- for (File f : file) {
- // 获取文件名称
- String fileName = f.getName();
- if (null != fileName && fileName.endsWith(".java")) {
- copyFile(
- f,
- new File(target + File.separator
- + fileName.replace(".java", ".txt")));
- }
- }
- }
- /**
- * 文件单独拷贝
- *
- * @param source
- * 数据源
- * @param target
- * 目标源
- */
- private static void copyFile(File source, File target) {
- //获取文件输入,输出流
- FileInputStream fis = null;
- FileOutputStream fos = null;
- try {
- fis = new FileInputStream(source);
- fos = new FileOutputStream(target);
- int length = 0;
- byte[] buf = new byte[1024];
- while ((length = fis.read(buf)) != -1) {
- fos.write(buf, 0, length);
- }
- } catch (IOException e) {
- e.printStackTrace();
- throw new RuntimeException("文件复制失败");
- } finally {
- // 关闭流
- try {
- if (fos != null)
- fos.close();
- } catch (IOException e) {
- throw new RuntimeException("写出文件关闭失败");
- }
- try {
- if (fis != null)
- fis.close();
- } catch (IOException e) {
- throw new RuntimeException("读取文件关闭失败");
- }
- }
- }
- }
复制代码
|
|