- package com.itheima;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.FilenameFilter;
- import java.io.InputStreamReader;
- /*
- * 问题:编写程序,将指定目录下所有.java文件拷贝到另一个目的中,并将扩展名改为.txt*/
- public class Test9
- {
- public static void main(String args[]) throws Exception{
- System.out.println("请输入文件所在的路径");
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- String path=br.readLine();
- // String path = "E:\\test";
- File root = new File(path);
- //判断路径
- if(! root.exists() && root.isDirectory()){
- System.out.println("路径有误!");
- }
- File[] files = root.listFiles(
- new FilenameFilter(){
- //文件名称过滤
- @Override
- public boolean accept(File dir, String name) {
- return name.endsWith(".java");
- }
- }
- );
-
- File targetFile = new File("d:\\a");
- if(! targetFile.exists()){
- //不存在则创建新目录
- targetFile.mkdir();
- }
- for(File file : files){
- FileInputStream fis = new FileInputStream(file);
- //名称替换
- String targetFileName = file.getName().replaceAll("\\.java$", ".txt");
- FileOutputStream fos = new FileOutputStream(new File(targetFile, targetFileName));
- FileCopy(fis, fos);
- fis.close();
- fos.close();
- }
- System.out.println("复制成功!");
- }
-
-
- private static void FileCopy(FileInputStream fis, FileOutputStream fos) throws Exception{
- byte[] data = new byte[1024];
- while(true){
- int len = fis.read(data);
- if(len == -1){
- break;
- }
- fos.write(data, 0, len);
- fos.flush();
- }
- }
- }
- //模仿的练了一下手
复制代码
|
|