FileInputStream通过字节的方式读取文件,适合读取所有类型的文件(图像、视频、文本文件等)。Java也提供了FileReader专门读取文本文件。
FileOutputStream 通过字节的方式写数据到文件中,适合所有类型的文件。Java也提供了FileWriter专门写入文本文件。
一、文件字节输入流(FileInputStream)
1 import java.io.*; 2 public class TestIO03 { 3 public static void main(String[] args) { 4 //创建源 5 File file = new File("b.txt"); 6 //选择流 7 InputStream inputStream = null; 8 try { 9 inputStream = new FileInputStream(file); 10 //操作流(分段读取),提高读取效率 11 byte[] flush = new byte[1024]; 12 int len = -1; //接收长度 13 while ((len = inputStream.read(flush)) != -1){ 14 //解码操作,字节数组-->字符串 15 String str = new String(flush,0,len); 16 System.out.println(str); 17 } 18 } catch (IOException e) { 19 e.printStackTrace(); 20 }finally { 21 //关闭流 22 if(inputStream!=null){ 23 try { 24 inputStream.close(); 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 } 29 } 30 } 31 }
二、文件字节输出流(FileOutputStream)
1 public class TestIO04 { 2 public static void main(String[] args) { 3 //创建源 4 File src = new File("abc.txt"); 5 //选择流 6 OutputStream outputStream = null; 7 try { 8 outputStream = new FileOutputStream(src); 9 //操作流(写出) 10 String msg = "IO is so esay"; 11 byte[] datas = msg.getBytes(); //字符串-->字节数组(编码) 12 outputStream.write(datas,0,datas.length); 13 outputStream.flush(); //刷新此输出流并强制任何缓冲的输出字节被写出,细节 14 } catch (FileNotFoundException ex) { 15 ex.printStackTrace(); 16 } catch (IOException e) { 17 e.printStackTrace(); 18 } finally { 19 //释放资源 20 if(outputStream!=null){ 21 try { 22 outputStream.close(); 23 } catch (IOException e) { 24 e.printStackTrace(); 25 } 26 } 27 } 28 } 29 30 }