day19;
package com.danjiang.test; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferWriterDemo { /** * 缓冲区的出现是为了提高流的操作效率而出现的 * * 所以在创建缓冲区之前,必须要先有流对象。 * * 该缓冲区中提供另外一个跨平台换行符。 newLine(); * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // 创建一个字符写入流对象。 FileWriter fw = new FileWriter("buf.txt"); // 为了提高字符写入流效率。加入了缓冲技术。 // 只要将需要被提高效率的流对象作为参数传递给缓冲区的构造函数即可。 BufferedWriter bufw = new BufferedWriter(fw); for (int i = 1; i < 5; i++) { bufw.write("abcd" + i); bufw.newLine(); bufw.flush(); } /* * bufw.write("abcd"); * * 记住,只要用到缓冲区。就要记得刷新。 bufw.flush(); * 其实关闭缓冲区,就是在关闭缓冲区的流对象.只需关闭缓冲bufw就行 */ bufw.close(); // fw.close(); } }
package com.danjiang.test; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class BufferedReaderDemo { /** * 字符读取流缓冲区: 该缓冲区提供了一个一次读一行的方法readLine,方法便于对文本数据的获取; 当返回null时,表示读到文件末尾。 * * readLine方法返回的时候只返回回车符之前的内容。并不返回回车符 * * @param args */ public static void main(String[] args) { try { // 创建一个读取流对象和文件相关联。 FileReader fr = new FileReader("buf.txt"); // 为了提高效率。加入了缓冲技术,将字符读取流对象作为参数传递给缓冲对象的构造函数。 BufferedReader bufr = new BufferedReader(fr); try { String line = null; while ((line = bufr.readLine()) != null) { System.out.println("line:" + line); } /* * String s1 = bufr.readLine(); System.out.println("s1:"+s1); * String s2 = bufr.readLine(); System.out.println("s2:"+s2); */ } catch (IOException e) { e.printStackTrace(); } try { bufr.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
package com.danjiang.test; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /* * 字符流 * FileReader * FilerWriter * * BufferedReader * BufferedWriter * * 字节流: * InputStream OutputStream * * 需求,想要操作图片数据。这事就要用到字节流。 * * * */ public class FileStream { /** * @param args */ public static void main(String[] args) throws IOException { // writeFile(); readerFile_3(); } public static void readerFile_3() throws IOException { FileInputStream fis = new FileInputStream("fos.txt"); // int a = fis.available(); // 定义一个刚刚好的缓冲区。不用再循环了 // 此方法慎用,如果读取问价比较大的话会导致内存溢出 byte[] buf = new byte[fis.available()]; fis.read(buf); System.out.println(new String(buf)); fis.close(); } public static void readerFile_2() throws IOException { // 此方法是最常用的方法,安全 FileInputStream fis = new FileInputStream("fos.txt"); byte[] buf = new byte[1024]; int len = 0; while ((len = fis.read(buf)) != -1) { System.out.println(new String(buf, 0, len)); } fis.close(); } public static void readerFile_1() throws IOException { FileInputStream fis = new FileInputStream("fos.txt"); int ch = 0; while ((ch = fis.read()) != -1) { // 读一个输出一行 System.out.println((char) ch); } } public static void writeFile() throws IOException { FileOutputStream fos = new FileOutputStream("fos.txt"); // 字符串转化为字节数组 fos.write("abcde".getBytes()); fos.close(); } }