将java 文件夹里面的.java 文件 拷贝到temp文件夹下,并且修改后缀名为.txt

来源:互联网 发布:windows 安装xcode教程 编辑:程序博客网 时间:2024/06/05 22:52
package cn.sdut.chapter6;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FilenameFilter;import java.util.Arrays;/* * 将java 文件夹里面的.java 文件 拷贝到temp文件夹下,并且修改后缀名为.txt */public class IOTest03 {//暂时不处理异常 抛出去 主要是文件拷贝和修改后缀名public static void main(String[] args) throws Exception{File srcdir = new File("java");File decdir = new File("temp");//首先找到java文件夹下面的.java文件File[] fs = null;if(srcdir.isDirectory()){//判断是不是目录 fs = srcdir.listFiles(new FilenameFilter() {//使用文件名过滤器过滤一下@Overridepublic boolean accept(File dir, String name) {return new File(dir,name).isFile()&& name.endsWith(".java");}});}//迭代出每个文件对象 并进行拷贝for(File srcFile : fs){FileInputStream in = new FileInputStream(srcFile);String name = srcFile.getName();//获取名称int index = name.lastIndexOf(".java");//取得后缀索引String newName = name.substring(0,index)+".txt";//修改System.out.println(newName);File newFile = new File(decdir,newName);/* * FileOutputStream out = new FileOutputStream(newFile); * 如果该文件存在,但它是一个目录,而不是一个常规文件;或者该文件不存在,但无法创建它;抑或因为其他某些原因而无法打开,则抛出 * FileNotFoundException。 *也就是如果文件不存在,如果文件可创建则FileOutputStream就创建 */FileOutputStream out = new FileOutputStream(newFile);int len;byte[] b = new byte[1024];while((len = in.read(b))!=-1){//进行拷贝 此时从a.java向a.text拷贝(我测试没问题,但是不知道不同格式之间拷贝会不会出现问题)out.write(b, 0, len);}in.close();out.close();}}}

阅读全文
0 0