字节流,字符流读取文件中的内容

  1.   一、使用字节流读取
  2. import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7.   
  8. public class Test08 {  
  9.   
  10.     public static void main(String[] args) {  
  11.         // 1.定义目标文件  
  12.         File srcFile = new File("E:/Temp/Test1.txt");  
  13.         // 2.创建一个流,指向目标文件  
  14.         InputStream is = null;  
  15.         try {  
  16.             is = new FileInputStream(srcFile);  
  17.             //3.创建一个用来存储读取数据的缓冲数组  
  18.             byte[]array = new byte[128];  
  19.             //4.循环往外流(count为每次读取数组中的有效字节总数)  
  20.             int count = is.read(array);  
  21.             // 5.循环打印  
  22.             while (count != -1) {  
  23.                 // 将byte[] -》 String  
  24.                 // 将byte数组读取到的有效字节转换成字符串  
  25.                 String string = new String(array, 0, count);  
  26.                 System.out.print(string);  
  27.                 count = is.read(array);  
  28.             }  
  29.         } catch (FileNotFoundException e) {  
  30.             e.printStackTrace();  
  31.         } catch (IOException e) {  
  32.             e.printStackTrace();  
  33.         } finally {  
  34.             // 关闭io流  
  35.             try {  
  36.                 is.close();  
  37.             } catch (IOException e) {  
  38.                 e.printStackTrace();  
  39.             }  
  40.         }  
  41.     }  
  42.   
  43. }  

二、使用字符流读取


[java]  view plain  copy
  1. package com.uwo9.test01;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileReader;  
  6. import java.io.IOException;  
  7. import java.io.Reader;  
  8.   
  9. public class Test08 {  
  10.   
  11.     public static void main(String[] args) {  
  12.         // 1.创建文件对象  
  13.         File fromFile = new File("E:/Temp/Test1.txt");  
  14.         // 2.创建字符输入流  
  15.         Reader reader = null;  
  16.         try {  
  17.             reader = new FileReader(fromFile);  
  18.             // 3.循环读取(打印)  
  19.             int content = reader.read();  
  20.             while (content != -1) {  
  21.                 System.out.print((char) content);  
  22.                 content = reader.read();  
  23.             }  
  24.         } catch (FileNotFoundException e) {  
  25.             e.printStackTrace();  
  26.         } catch (IOException e) {  
  27.             e.printStackTrace();  
  28.         }finally {  
  29.             // 4.关闭流  
  30.             try {  
  31.                 reader.close();  
  32.             } catch (IOException e) {  
  33.                 e.printStackTrace();  
  34.             }  
  35.         }  
  36.           
  37.           
  38.   
  39.     }  
  40.   
  41. }  

猜你喜欢

转载自blog.csdn.net/fight_man8866/article/details/80736657