标签:
package io; import java.util.regex.*; import java.io.*; import java.util.*; public class DirList3 { public static void main(final String[] args) { File path = new File("./src/io"); String[] list; if(args.length == 0) list = path.list(); else list = path.list(new FilenameFilter() { private Pattern pattern = Pattern.compile(args[0]); public boolean accept(File dir, String name) { return pattern.matcher(name).matches(); } }); Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); for(String dirItem : list) System.out.println(dirItem); } }
//这个是JDK底层源代码,对于带参的list()的实现:
public String[] list(FilenameFilter filter) { String names[] = list(); if ((names == null) || (filter == null)) { return names; } ArrayList v = new ArrayList(); for (int i = 0 ; i < names.length ; i++) { if (filter.accept(this, names[i])) { v.add(names[i]); } } return (String[])(v.toArray(new String[v.size()])); }
package utils; import java.util.regex.*; import java.io.*; import java.util.*; /** * 文件和目录的工具类 * final类:不可被继承的类 * @author Administrator * */ public final class Directory { /** * function:根据传入的file目录和正则表达式,获取该目录中的文件构成的File对象数组 * @param dir * @param regex * @return 返回满足指定过滤器的抽象路径名表示的目录下的文件和目录的数组 */ public static File[] local(File dir, final String regex) { return dir.listFiles(new FilenameFilter() { private Pattern pattern = Pattern.compile(regex);//设置正则表达式 public boolean accept(File dir, String name) { return pattern.matcher(new File(name).getName()).matches(); } }); } //Overloaded public static File[] local(String path, final String regex) { return local(new File(path), regex); } /** * 内部静态类 * @author Administrator * */ public static class TreeInfo implements Iterable<File> { public List<File> files = new ArrayList<File>(); public List<File> dirs = new ArrayList<File>(); // The default iterable element is the file list: public Iterator<File> iterator() { return files.iterator(); } void addAll(TreeInfo other) { files.addAll(other.files); dirs.addAll(other.dirs); } public String toString() { return "dirs: " + PPrint.pformat(dirs) + "\n\nfiles: " + PPrint.pformat(files); } } public static TreeInfo walk(String start, String regex) { // Begin recursion return recurseDirs(new File(start), regex); } public static TreeInfo walk(File start, String regex) { // Overloaded return recurseDirs(start, regex); } public static TreeInfo walk(File start) { // Everything return recurseDirs(start, ".*"); } public static TreeInfo walk(String start) { return recurseDirs(new File(start), ".*"); } /** * * @param startDir * @param regex * @return */ static TreeInfo recurseDirs(File startDir, String regex){ TreeInfo result = new TreeInfo(); for(File item : startDir.listFiles()) { if(item.isDirectory()) { result.dirs.add(item); result.addAll(recurseDirs(item, regex)); } else // Regular file if(item.getName().matches(regex)) result.files.add(item); } return result; } // Simple validation test: public static void main(String[] args) { if(args.length == 0) System.out.println(walk(".")); else for(String arg : args) System.out.println(walk(arg)); } }
上面这些类的使用具体可以去参考JDK的文档。我们可以发现对于文件的读写类大都是成对出现的,InputStream或则Reader实现读取(从流中读取),OutputStream或则Writer实现写入功能(输出至流)。这里的流可以是控制台,可以是文件,也可以是Internet。
- java.lang.Object
- java.io.File (implements java.lang.Comparable<T>, java.io.Serializable)
- java.io.InputStream (implements java.io.Closeable)
- java.io.ByteArrayInputStream
- java.io.FileInputStream
- java.io.FilterInputStream
- java.io.BufferedInputStream
- java.io.DataInputStream (implements java.io.DataInput)
- java.io.LineNumberInputStream
- java.io.PushbackInputStream
- java.io.ObjectInputStream (implements java.io.ObjectInput, java.io.ObjectStreamConstants)
- java.io.PipedInputStream
- java.io.SequenceInputStream
- java.io.StringBufferInputStream
- java.io.OutputStream (implements java.io.Closeable, java.io.Flushable)
- java.io.ByteArrayOutputStream
- java.io.FileOutputStream
- java.io.FilterOutputStream
- java.io.BufferedOutputStream
- java.io.DataOutputStream (implements java.io.DataOutput)
- java.io.PrintStream (implements java.lang.Appendable, java.io.Closeable)
- java.io.ObjectOutputStream (implements java.io.ObjectOutput, java.io.ObjectStreamConstants)
- java.io.RandomAccessFile (implements java.io.Closeable, java.io.DataInput, java.io.DataOutput)
- java.io.Reader (implements java.io.Closeable, java.lang.Readable)
- java.io.BufferedReader
- java.io.LineNumberReader
- java.io.CharArrayReader
- java.io.FilterReader
- java.io.PushbackReader
- java.io.InputStreamReader
- java.io.FileReader
- java.io.PipedReader
- java.io.StringReader
- java.io.Writer (implements java.lang.Appendable, java.io.Closeable, java.io.Flushable)
- java.io.BufferedWriter
- java.io.CharArrayWriter
- java.io.FilterWriter
- java.io.OutputStreamWriter
- java.io.FileWriter
- java.io.PipedWriter
- java.io.PrintWriter
- java.io.StringWriter
package io.input; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * 缓冲输入文件 * 打开一个文件用于字符输入,读取字符 * @author Administrator */ public class BufferedInputFile { /** * @param fileName 文件名 * @return 文件内的字符串 * @throws IOException */ public static String read(String fileName) throws IOException { //inputStream输入流 //创建一个(使用默认大小输入缓冲区的)缓冲字符输入流 BufferedReader in = new BufferedReader( new FileReader(fileName)); String s= null; StringBuilder sb = new StringBuilder(); while( (s = in.readLine()) != null ) { sb.append(s + "\n"); } in.close(); return sb.toString(); } /* * testing */ public static void main(String[] args) throws IOException { System.out.println( read("./src/io/BufferedInputFile.java") ); } }
package io.input; import java.io.IOException; import java.io.StringReader; /** * 从内存输入 * @author Administrator */ public class MemoryInput { public static void main(String[] args) throws IOException { String str = BufferedInputFile.read("./src/io/MemoryInput.java"); //str这时存放在内存中 //StringReader :源为字符串的字符流 StringReader in = new StringReader(str); int c = 0; while ( (c = in.read()) != -1) { System.out.print( (char)c ); } } }
package io.input; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; /** * 格式化的内存输入:面向字节读取(8位),而我们一般的字符读取是16位,所以字节读取出来的中文是乱码 * 所以必须使用inputStream。不能使用Reader * @author Administrator * */ public class FormattedMemoryInput { public static void main(String[] args) throws IOException { /* try { //先读取java文件的字符串并转换成 字节数组 byte[] bs = BufferedInputFile.read("./src/io/FormattedMemoryInput.java").getBytes(); //创建字节数组输入流 ByteArrayInputStream ins = new ByteArrayInputStream(bs); //创建输入流 DataInputStream in = new DataInputStream(ins); while(true){ System.out.print( (char)in.readByte() ); } } catch (EOFException e) { System.err.println("end"); } */ //先读取java文件的字符串并转换成 字节数组 byte[] bs = BufferedInputFile.read("./src/io/FormattedMemoryInput.java").getBytes(); //创建字节数组输入流 ByteArrayInputStream ins = new ByteArrayInputStream(bs); //创建输入流 DataInputStream in = new DataInputStream(ins); while( in.available() != 0){ System.out.print( (char)in.readByte() ); } } }
package io.output; import io.input.BufferedInputFile; import java.io.*; public class FileOutputShortcut { static String file = "./src/io/output/FileOutputShortcut.java"; static String fileOut = "./src/io/output/FileOutputShortcut.out"; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(file)); //此处简化了 PrintWriter out = new PrintWriter(fileOut); int lineCount = 1; String s; while((s = in.readLine()) != null ) out.println(lineCount++ + ": " + s); in.close(); out.close(); System.out.println(BufferedInputFile.read(fileOut)); } }
package utils; import java.io.*; import java.util.*; /** * function:提供一些静态方法,像简单字符串一样读写文件 * //字符形式 * @author Administrator * */ public class TextFile extends ArrayList<String> { private static final long serialVersionUID = 2025881288414881601L; /** * function:读取一个文件,返回文件内容的字符串形式 * @param fileName * @return */ public static String read(String fileName) { StringBuilder sb = new StringBuilder(); try { //获取的绝对路径(磁盘名开始) BufferedReader in= new BufferedReader(new FileReader( new File(fileName).getAbsoluteFile())); try { String s; while((s = in.readLine()) != null) { sb.append(s); sb.append("\n"); } } finally { in.close(); } } catch(IOException e) { throw new RuntimeException(e); } return sb.toString(); } /** * function:往文件里面写入一个字符串 * @param fileName * @param text */ public static void write(String fileName, String text) { try { PrintWriter out = new PrintWriter( new File(fileName).getAbsoluteFile()); try { out.print(text); } finally { out.close(); } } catch(IOException e) { throw new RuntimeException(e); } } /** * function:构造器: * 读一个文件返回字符串,并以一个正则表达式分离,然后保存在一个ArrayList中 */ public TextFile(String fileName, String splitter) { super( Arrays.asList( read(fileName).split(splitter) ) ); if(get(0).equals("")) remove(0); } /** * function:构造器 * 默认以换行符为正则 * @param fileName */ public TextFile(String fileName) { this(fileName, "\n"); } public void write(String fileName) { try { PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile()); try { for(String item : this) out.println(item); } finally { out.close(); } } catch(IOException e) { throw new RuntimeException(e); } } //main 测试 public static void main(String[] args) { String file = read("./src/utils/TextFile.java"); write("./src/utils/test.txt", file); TextFile text = new TextFile("./src/utils/test.txt"); text.write("./src/utils/test2.txt"); TreeSet<String> words = new TreeSet<String>( new TextFile("./src/utils/TextFile.java", "\\W+")); System.out.println(words.headSet("a")); } }
package utils; import java.io.*; /** * function:读取二进制格式的文件 * @author Administrator * */ public class BinaryFile { public static byte[] read(File bFile) throws IOException{ BufferedInputStream bf = new BufferedInputStream( new FileInputStream(bFile) ); try { byte[] data = new byte[bf.available()]; bf.read(data);//从此输入流中将 byte.length个字节的数据读入 data数组中。 return data; } finally { bf.close(); } } public static byte[] read(String bFile) throws IOException { return read( new File(bFile).getAbsoluteFile() ); } }
package io; import java.io.*; public class Echo { public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String s; while((s = stdin.readLine()) != null && s.length()!= 0) System.out.println(s); } }
package io; import java.io.*; /** * 标准IO重定向,可以吧控制台输出到指定文件中,类似于日志 * @author Administrator */ public class Redirecting { public static void main(String[] args) throws IOException { PrintStream console = System.out; BufferedInputStream in = new BufferedInputStream( new FileInputStream("./src/io/Redirecting.java")); PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream("./src/io/test.out"))); System.setIn(in); System.setOut(out);//标准输出输出重定向到test.out这个文件中。 System.setErr(out);//标准输出输出重定向到test.out这个文件中。 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s; while((s = br.readLine()) != null && s.length()!= 0 ) System.out.println(s); out.close(); // Remember this! System.setOut(console); } }
标签:
原文地址:http://blog.csdn.net/u010853261/article/details/51459704