张孝祥老师的java就业题目里的,实用的,保存下 java.io.File; |
02 | import java.io.FileInputStream; |
03 | import java.io.FileOutputStream; |
04 | import java.io.FilenameFilter; |
05 | import java.io.IOException; |
06 | import java.io.InputStream; |
07 | import java.io.OutputStream; |
08 |
09 |
10 | public class java2txt { |
11 |
12 | /** |
13 | * @param args |
14 | */ |
15 | public static void main(String[] args) throws Exception { |
16 | // TODO Auto-generated method stub |
17 |
18 | File srcDir = new File( "d:\\java" ); |
19 | if ( ! (srcDir.exists() && srcDir.isDirectory())) { |
20 | throw new Exception( "目录不存在!" ); |
21 | } |
22 | File[] files = srcDir.listFiles( new FilenameFilter() { // 文件扩展名过滤器 |
23 | |
24 | public boolean accept(File dir, String name) { |
25 | return name.endsWith( "java" ); |
26 | } |
27 | |
28 | }); |
29 | System.out.println(files.length); |
30 | |
31 | File destDir = new File( "d:\\txt" ); |
32 | if (!destDir.exists()) |
33 | destDir.mkdir(); |
34 | for (File f : files) { // 此循环语句写法推荐 |
35 | FileInputStream fis = new FileInputStream(f); |
36 | String destFileName = f.getName().replaceAll( "\\.java$" , ".txt" ); |
37 | FileOutputStream fos = new FileOutputStream( new File(destDir, destFileName)); |
38 | copy(fis, fos); |
39 | fis.close(); |
40 | fos.close(); |
41 | } |
42 | } |
43 | |
44 | // 流的方式读取文件,存在着byte数组中 |
45 | public static void copy(InputStream ips, OutputStream ops) throws IOException { |
46 | int len = 0 ; |
47 | byte [] buf = new byte [ 1024 ]; |
48 | while ((len = ips.read(buf)) != - 1 ) { |
49 | ops.write(buf, 0 , len); |
50 | } |
51 | } |
52 |
53 | } |