Reader: FileReader BufferedReader
Writer: FileWriter BufferedWriter
字符流读取写入文件都有这两种
单独用FileWriter写入文件会每次写入数据,磁盘都有一次写入导致效率低,使用BufferReader搭配使用会把缓冲区装满再进行写入,提高了写入的效率。
try { BufferedWriter bw = new BufferedWriter(new FileWriter("aa1.txt", true)); for (int i = 0; i < 10; i++) { bw.append("holle world!中文效果\n"); } bw.flush(); bw.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("字符流:"); var m1 = System.currentTimeMillis(); try { BufferedReader br = new BufferedReader(new FileReader("aa1.txt")); while (br.ready()) { System.out.println(br.readLine()); } System.out.printf("字符流时间:%d毫秒%n", System.currentTimeMillis() - m1); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
java.io.InputStream 输入流,主要是用来读取文件内容的。
java.io.OutputStream 输出流,主要是用来将内容字节写入文件的
System.out.println("字节流:"); try { var m2 = System.currentTimeMillis(); BufferedInputStream bis = new BufferedInputStream(new FileInputStream("aa1.txt")); byte[] s = new byte[1024]; int aa = 0; while ((aa = bis.read(s)) > 0) { System.out.println(new String(s, 0, aa)); } bis.close(); System.out.printf("字节流时间:%d毫秒%n", System.currentTimeMillis() - m2); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
byte[] s就是建立缓冲区读取字节