处理流
处理类型 | 字符流 | 字节流 |
Buffering |
BufferReader BufferWriter |
BufferedInputStream BufferedOutputStream |
Converting between bytes and character |
InputStreamReader OutputStreamWriter |
|
Object Serialization | --- |
ObjectInputStream ObjectOutputstream |
Data Conversion | --- |
DataInputStream DataOutputStream |
Counting | LineNumberReader | LineNumberInputStream |
Peeking ahead | PushbackReader |
PushbackInputStream |
Printing | PrintWriter | PrintStream |
1,缓冲流
缓冲流要“套接”在相应的节点流之上,对读写的数据提供了缓冲的功能,提高了读写的效率,同时增加了一些新的方法。
J2SDK提供了四种缓冲流,其常用的构造方法:
BufferedReader BufferedReader(Reader in) Creates a buffering character-input stream that uses a default-sized input buffer. BufferedReader(Reader in, int sz) Creates a buffering character-input stream that uses an input buffer of the specified size. BufferedWriter BufferedWriter(Writer out) Creates a buffered character-output stream that uses a default-sized output buffer. BufferedWriter(Writer out, int sz) Creates a new buffered character-output stream that uses an output buffer of the given size. BufferedInputStream BufferedInputStream(InputStream in) Creates a BufferedInputStream and saves its argument, the input stream in, for later use. BufferedInputStream(InputStream in, int size) Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in, for later use. BufferedOutputStream BufferedOutputStream(OutputStream out) Creates a new buffered output stream to write data to the specified underlying output stream. BufferedOutputStream(OutputStream out, int size) Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.
缓冲输入流支持其父类的mark和reset方法 BufferedReader提供了readLine方法用于读取一行字符串(以\r或\n分隔) BufferedWriter提供了newLine方法用于写入一个行分隔符 对于输出的缓冲流,写出的数据会先在内存中缓存,使用flush方法将会使内存中的数据立刻写出。
例子一
public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("d:\\share\\java\\HelloWorld.java"); BufferedInputStream bis = new BufferedInputStream(fis); int c = 0; System.out.println(bis.read()); System.out.println(bis.read()); bis.mark(100); for(int i = 0; i <= 10 && (c=bis.read()) != -1; i++) { System.out.print((char)c + " "); } System.out.println(); bis.reset(); for(int i = 0; i <= 10 && (c=bis.read()) != -1; i++) { System.out.print((char)c + " "); } bis.close(); } catch (IOException e) { e.printStackTrace(); } }
结果:
4742 a l ; s k j d f ; a l ; s k j d f ;
例子二、
public static void main(String[] args) { try { BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\dat2.txt")); BufferedReader br = new BufferedReader(new FileReader("d:\\dat2.txt")); String s = null; for(int i = 1; i<=100; i++) { s = String.valueOf(Math.random()); bw.write(s); bw.newLine(); } bw.flush(); while((s = br.readLine()) != null) {//读一行 System.out.println(s); } bw.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } }
结果:
dat2.txt文件:
控制台输出:
时间: 2024-11-07 22:54:14