1.File类
File类既能代表一个特定文件的名称,又能代表一个目录下的一组文件的名称。
如果我们调用不带参数的list()
方法,便可以获得此File对象包含的全部列表。然而,如果我们想获得一个受限列表,例如,想得到所有扩展名为.java的文件,那么我们就要用到“目录过滤器”,这个类告诉我们怎样显示符合条件的File对象。
import java.util.regex.*;import java.io.*;import java.util.*;public class DirList3 { public static void main(final String[] args) { File path = new File("."); 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); } }}
File类不仅仅只代表存在的文件或目录。也可以用File对象来创建新的目录或尚不存在的整个目录路径。我们还可以查看文件的特性(例如,大小、最后修改日期、读/写),检查某个File对象代表的是一个文件还是一个目录,并可以删除文件。
import java.io.*;public class MakeDirectories { private static void usage() { System.err.println( "Usage:MakeDirectories path1 ...\n" + "Creates each path\n" + "Usage:MakeDirectories -d path1 ...\n" + "Deletes each path\n" + "Usage:MakeDirectories -r path1 path2\n" + "Renames from path1 to path2"); System.exit(1); } private static void fileData(File f) { System.out.println( "Absolute path: " + f.getAbsolutePath() + "\n Can read: " + f.canRead() + "\n Can write: " + f.canWrite() + "\n getName: " + f.getName() + "\n getParent: " + f.getParent() + "\n getPath: " + f.getPath() + "\n length: " + f.length() + "\n lastModified: " + f.lastModified()); if(f.isFile()){ System.out.println("It's a file"); }else if(f.isDirectory()){ System.out.println("It's a directory"); } } public static void main(String[] args) { if(args.length < 1){ usage(); } if(args[0].equals("-r")) { if(args.length != 3){ usage(); } File old = new File(args[1]),rname = new File(args[2]); old.renameTo(rname); fileData(old); fileData(rname); return; // Exit main } int count = 0; boolean del = false; if(args[0].equals("-d")) { count++; del = true; } count--; while(++count < args.length) { File f = new File(args[count]); if(f.exists()) { System.out.println(f + " exists"); if(del) { System.out.println("deleting..." + f); f.delete(); } }else { // Doesn't exist if(!del) { f.mkdirs(); System.out.println("created " + f); } } fileData(f); } }}
2.字节流
编程语言的I/O类库中常使用流这个抽象概念,它代表任何有能力产出数据的数据源对象或者是有能力接收数据的接收端对象。
Java类库中的I/O类分成输入和输出两部分。 与输入有关的所有类都应该从InputStream
继承,而与输出有关的所有类都应该从OutputStream
继承。 3.字符流
Reader
和Writer
提供兼容Unicode与面向字符的I/O功能。
有时我们必须把来自于“字节”层次结构中的类和“字符”层次结构中的类结合起来使用。为了实现这个目的,要用到适配器类:InputStreamReader
可以把InputStream
转换为Reader
,而OutputStreamWriter
可以把OututStream
转换为Writer
。
4.I/O流的典型使用方式
4.1 缓冲输入文件
import java.io.*;public class BufferedInputFile { // Throw exceptions to console: public static String read(String filename) throws IOException { // Reading input by lines: BufferedReader in = new BufferedReader(new FileReader(filename)); String s; StringBuilder sb = new StringBuilder(); while((s = in.readLine())!= null){ sb.append(s + "\n"); } in.close(); return sb.toString(); } public static void main(String[] args) throws IOException { System.out.print(read("BufferedInputFile.java")); }}
4.2 从内存输入
public class MemoryInput { public static void main(String[] args) throws IOException { StringReader in = new StringReader(BufferedInputFile.read("MemoryInput.java")); int c; while((c = in.read()) != -1){ System.out.print((char)c); } }}
4.3 格式化的内存输入
public class FormattedMemoryInput { public static void main(String[] args) throws IOException { try { DataInputStream in = new DataInputStream(new ByteArrayInputStream(BufferedInputFile.read("FormattedMemoryInput.java").getBytes())); while(true){ System.out.print((char)in.readByte()); } }catch(EOFException e) { System.err.println("End of stream"); } }}
public class TestEOF { public static void main(String[] args) throws IOException { DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("TestEOF.java"))); while(in.available() != 0){ System.out.print((char)in.readByte()); } }}
4.4 基本的文件输入
import java.io.*;public class BasicFileOutput { static String file = "BasicFileOutput.out"; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new StringReader(BufferedInputFile.read("BasicFileOutput.java"))); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file))); // Here's the shortcut: //PrintWriter out = new PrintWriter(file); int lineCount = 1; String s; while((s = in.readLine()) != null ){ out.println(lineCount++ + ": " + s); } out.close(); // Show the stored file: System.out.println(BufferedInputFile.read(file)); }}
4.5 存储和恢复数据
import java.io.*;public class StoringAndRecoveringData { public static void main(String[] args) throws IOException { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("Data.txt"))); out.writeDouble(3.14159); out.writeUTF("That was pi"); out.writeDouble(1.41413); out.writeUTF("Square root of 2"); out.close(); DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("Data.txt"))); System.out.println(in.readDouble()); // Only readUTF() will recover the // Java-UTF String properly: System.out.println(in.readUTF()); System.out.println(in.readDouble()); System.out.println(in.readUTF()); }}
4.6 读写随机访问文件
import java.io.*;public class UsingRandomAccessFile { static String file = "rtest.dat"; static void display() throws IOException { RandomAccessFile rf = new RandomAccessFile(file, "r"); for(int i = 0; i < 7; i++){ System.out.println("Value " + i + ": " + rf.readDouble()); } System.out.println(rf.readUTF()); rf.close(); } public static void main(String[] args) throws IOException { RandomAccessFile rf = new RandomAccessFile(file, "rw"); for(int i = 0; i < 7; i++){ rf.writeDouble(i*1.414); } rf.writeUTF("The end of the file"); rf.close(); display(); rf = new RandomAccessFile(file, "rw"); rf.seek(5*8); rf.writeDouble(47.0001); rf.close(); display(); }}
5.标准I/O
从标准输入中读取
按照标准I/O模型,Java提供了System.in
、System.out
和System.err
。 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); } // An empty line or Ctrl-Z terminates the program }}
将System.out
转换成PrintWriter
import java.io.*;public class ChangeSystemOut { public static void main(String[] args) { PrintWriter out = new PrintWriter(System.out, true); out.println("Hello, world"); }}
标准I/O重定向
import java.io.*;public class Redirecting { public static void main(String[] args) throws IOException { PrintStream console = System.out; BufferedInputStream in = new BufferedInputStream(new FileInputStream("Redirecting.java")); PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream("test.out"))); //setIn(InputStream)、setOut(PrintStream)和setErr(PrintStream)对标准输入、输出和错误I/O流进行重定向。 System.setIn(in); System.setOut(out); System.setErr(out); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s; while((s = br.readLine()) != null){ System.out.println(s); } out.close(); // Remember this! System.setOut(console); }}
6.NIO
相关阅读: