1、字节形式读取
1 @Test 2 public void test1(){ 3 String path = "d://temp/test.txt"; 4 readFile(path); 5 } 6 7 private void readFile(String path) { 8 //FileInputStream 用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader 9 File file = new File(path); 10 InputStream in = null; 11 try { 12 in = new FileInputStream(file); 13 int tempStr = 0; 14 while((tempStr = in.read())!=-1){ 15 System.out.write(tempStr); 16 } 17 } catch (FileNotFoundException e) { 18 // TODO Auto-generated catch block 19 e.printStackTrace(); 20 } catch (IOException e) { 21 // TODO Auto-generated catch block 22 e.printStackTrace(); 23 } 24 }
改进方式一次读取多个字节
1 private void readFile(String path) { 2 //FileInputStream 用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader 3 File file = new File(path); 4 InputStream in = null; 5 try { 6 in = new FileInputStream(file); 7 byte[] byteArr = new byte[1024]; 8 while(in.read(byteArr)!=-1){ 9 System.out.write(byteArr); 10 } 11 } catch (FileNotFoundException e) { 12 // TODO Auto-generated catch block 13 e.printStackTrace(); 14 } catch (IOException e) { 15 // TODO Auto-generated catch block 16 e.printStackTrace(); 17 } 18 }
2、字符形式读取
1 private void readFile(String path) { 2 File file = new File(path); 3 InputStreamReader in = null; 4 try { 5 in = new InputStreamReader(new FileInputStream(file)); 6 int tempStr; 7 while((tempStr=in.read())!=-1){ 8 System.out.write(tempStr); 9 } 10 } catch (FileNotFoundException e) { 11 // TODO Auto-generated catch block 12 e.printStackTrace(); 13 } catch (IOException e) { 14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 } finally { 17 if(in!=null) 18 try { 19 in.close(); 20 } catch (IOException e) { 21 // TODO Auto-generated catch block 22 e.printStackTrace(); 23 } 24 } 25 }
改进方式
1 private void readFile(String path) { 2 File file = new File(path); 3 InputStreamReader in = null; 4 try { 5 in = new InputStreamReader(new FileInputStream(file)); 6 char[] charArr = new char[1024]; 7 while(in.read(charArr)!=-1){ 8 System.out.print(charArr); 9 } 10 } catch (FileNotFoundException e) { 11 // TODO Auto-generated catch block 12 e.printStackTrace(); 13 } catch (IOException e) { 14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 } finally { 17 if(in!=null) 18 try { 19 in.close(); 20 } catch (IOException e) { 21 // TODO Auto-generated catch block 22 e.printStackTrace(); 23 } 24 } 25 }
3、以行为单位读取文件,常用于读面向行的格式化文件,如csv等
1 private void readFile(String path) { 2 File file = new File(path); 3 BufferedReader in = null; 4 try { 5 in = new BufferedReader(new FileReader(file)); 6 String tempStr = ""; 7 while((tempStr=in.readLine()) != null){ 8 System.out.println(tempStr); 9 } 10 } catch (FileNotFoundException e) { 11 // TODO Auto-generated catch block 12 e.printStackTrace(); 13 } catch (IOException e) { 14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 } finally { 17 if(in!=null) 18 try { 19 in.close(); 20 } catch (IOException e) { 21 // TODO Auto-generated catch block 22 e.printStackTrace(); 23 } 24 } 25 }