file input stream:(n次外层往内存读取)
1.在本地建立text文本文件:
2.在eclipse中输入代码:
1 import java.io.FileInputStream; 2 import java.io.IOException; 3 4 public class FileInputStreamDemo { 5 public static void main(String args[]) { 6 int i; 7 char c; 8 try(FileInputStream f=new FileInputStream("G:\学习型文档\java_test")){ 9 while((i=f.read())!=-1) { 10 System.out.println(" "+i); 11 c=(char ) i; 12 System.out.println(c); 13 } 14 } 15 catch(IOException ex) { 16 System.out.println(ex); 17 } 18 19 } 20 21 }
测试结果:
???:
拒绝访问的原因:
原因;
FileInputStream ff=new FileInputStream("G:\学习型文档\java_test\file.txt");
注:但内存访问磁盘比较耗时(文件中有几个字符读取几次),于是考虑buffereldinputstream:
高速缓存。不是从文件中读取字符串。直接用字符串做输入流(一次读取文件)
用该输入流做缓冲输入流的参数:
1 import java.io.BufferedInputStream; 2 import java.io.FileInputStream; 3 import java.io.IOException; 4 5 public class BufferedReaderDemo { 6 public static void main(String args[]){ 7 String s ="This is a BufferedInputStream Demo Program"; 8 byte buf[] =s.getBytes(); 9 try( 10 //ByteArrayInputStream in =new ByteArrayInputStream(buf); 11 FileInputStream ff=new FileInputStream("G:\学习型文档\java_test\file.txt"); 12 BufferedInputStream f=new BufferedInputStream(ff)){ 13 int c; 14 char t; 15 while((c=f.read())!=-1) { 16 t=(char)c; 17 System.out.println(t); 18 } 19 20 } 21 catch(IOException e) { 22 System.out.println(e); 23 } 24 } 25 26 }
测试结果:
一次外层往内存读取
(内存高速缓冲区的对象:是f-ff进行文件字符串数数码的读取)------n次高速缓存往内存读取