- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.FilenameFilter;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- public class java2txt {
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- File srcDir = new File("d:\\\\java");
- if ( ! (srcDir.exists() && srcDir.isDirectory())) {
- throw new Exception("目录不存在!");
- }
- File[] files = srcDir.listFiles(new FilenameFilter() {// 文件扩展名过滤器
- public boolean accept(File dir, String name) {
- return name.endsWith("java");
- }
- });
- System.out.println(files.length);
- File destDir = new File("d:\\\\txt");
- if (!destDir.exists())
- destDir.mkdir();
- for(File f : files) {// 此循环语句写法推荐
- FileInputStream fis = new FileInputStream(f);
- String destFileName = f.getName().replaceAll("\\\\.java$", ".txt");
- FileOutputStream fos = new FileOutputStream(new File(destDir, destFileName));
- copy(fis, fos);
- fis.close();
- fos.close();
- }
- }
- // 流的方式读取文件,存在着byte数组中
- public static void copy(InputStream ips, OutputStream ops) throws IOException {
- int len = 0;
- byte[] buf = new byte[1024];
- while((len = ips.read(buf)) != -1) {
- ops.write(buf, 0, len);
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/020820134939.html
来源: http://www.codesnippet.cn/detail/020820134939.html