• Java的IO流


    原文地址:http://blog.csdn.net/lihuapiao/article/details/50731405

    一.IO

    1.IO概念

      ·输入流:把能够读取一个字节序列的对象称为输入流(百度百科)

      ·输出流:把能够写一个字节序列的对象称为输出流(百度百科)

              从定义上看可能会让你感到困惑,这里解释一下:输入输出是相对于内存设备而言的,将外设(硬盘,键盘等)中的数据读取到内存设备中叫输入;将内存设备中的数据写入到外设中叫输出,所以有读入,写出的称呼:读入到内存,写出内存。

              可以这样比喻:输入流和输出流中间连接着内存,输入流和输出流将读写分离开来进行操作,先从外设读入内存,然后再写出内存转移到其他外设。

       ·总体结构图(摘自网友)


    2.字节流      (用字节流处理字符数据可能会有编码问题,因为字节流是以字节为单位,没有编码,而字符流是以字符为单位传送数据,字符流即以字节流+编码)

      ·两个顶层父类 (抽象类)及实现类

            ·InputStream(读入内存)  :所有字节输入流相关类的父类

                  ··FileInputStream :obtain input bytes from a file in a file system,for reading streams of raw bytes(原始字节) such as image data..For writing streams of characters,consider using FileReader

                           初始化时(构造函数)要和文件关联,读取的对象,要首先判断文件是否存在

                         ——read():read a byte of data from this inputStream.

                         ——read(byte [] b):read up to b.length bytes of data from this inputStream into an array of bytes.

                         ——read(byte [] b,int off,int length)

                         ——close()

              

    1. import java.io.*;  
    2.   
    3. /** 
    4.  * Created by 111 on 2016/1/29. 
    5.  */  
    6. public class Demo1 {  
    7.   
    8.     public static void main(String [] args){  
    9.         File file = new File("d:/helloWorld.txt");  
    10.         InputStream in = null;  
    11.         try {  
    12.             if (!file.exists()){                              //文件不存在则创建  
    13.                 file.createNewFile();  
    14.             }  
    15.             in = new FileInputStream(file);  
    16.             byte [] buf = new byte[1024];                 //先写到缓存中,然后再一起写到其他外设中  
    17.             int length = 0;                           
    18.             while ((length=in.read(buf))!=-1){                //-1 represent the end of the file is reached    ,  
    19.                                                             //字节一个一个地读入到内存  
    20.                 System.out.println(new String(buf,0,length)); //需要将int转为字节,如果为中文的话输出乱码字符  ,  
    21.                                                      //此处其实是写出到了外设(控制台)上,System.out返回的是PrintStream对象  
    22.             }  
    23.         } catch (IOException e) {  
    24.             e.printStackTrace();  
    25.         }finally {  
    26.             if (in != null){  
    27.                 try {  
    28.                     in.close();  
    29.                 } catch (IOException e) {  
    30.                     e.printStackTrace();  
    31.                 }  
    32.             }  
    33.         }  
    34.     }  

                   ··ByteArrayInputStream:包含一个内置的缓冲器存储字节

                          构造函数要和字节数组相关联:byte [] buff

                          ——read():从输入流中读取下一个字节

                          ——read(byte [] buff,int off,int len):

                          ——close():关闭后并没有影响,类中的方法仍然可以调用而不抛出IO异常

            ·OutputStream(写出内存):所有和输出字节流相关类的父类

                   ··FileOutputStream:for writing data to a file or a FileDescriptor,for writing streams of raw data(原始字节)such as image data.For writing streams of characters,consider using FileWriter.

                        初始化时要和文件关联,写出的目的地。没有该文件时会自动创建。

                        ——write(int b):write the specified(指定的) byte to this file output stream.

                        ——write(byte [] b):

                        ——write(byte [] b,int off,int len)

                        ——close()

    1. import java.io.*;  
    2.   
    3. /** 
    4.  * Created by 111 on 2016/2/25. 
    5.  */  
    6. public class Demo2 {  
    7.     public static void main(String [] args){  
    8.         File file = new File("d:/helloWorld3.txt");   //没有<span style="font-family:KaiTi_GB2312;">会自动创建</span>  
    9.         OutputStream out = null;  
    10.         try {  
    11.             out = new FileOutputStream(file);  
    12.             out.write(69);                    //文件中产生ASC码对应的字符  
    13.         } catch (IOException e) {  
    14.             e.printStackTrace();  
    15.         } finally {  
    16.             try {  
    17.                 out.close();  
    18.             } catch (IOException e) {  
    19.                 e.printStackTrace();  
    20.             }  
    21.         }  
    22.     }  
    23. }  


           ★ FileInputStream  & FileOutputStream   协同完成文件复制(不会乱码)

    1. import java.io.*;  
    2.   
    3. /** 
    4.  * Created by 111 on 2016/2/25. 
    5.  */  
    6. public class Demo3 {  
    7.     /** 
    8.      * 从一个文件复制到另一个文件 
    9.      * @param args 
    10.      */  
    11.     public static void main(String [] args){  
    12.         File origin = new File("d:/helloWorld.txt");//原始文件  
    13.         if (!origin.exists()){  
    14.             try {  
    15.                 origin.createNewFile();  
    16.             } catch (IOException e) {  
    17.                 e.printStackTrace();  
    18.             }  
    19.         }  
    20.         File destination = new File("d:/helloWorld4.txt");//目的文件  
    21.         InputStream in = null;  
    22.         OutputStream out = null;  
    23.         try {  
    24.             in = new FileInputStream(origin);  
    25.             out = new FileOutputStream(destination);  
    26.             byte [] buff = new byte[1024];  
    27.             int len = 0;  
    28.             while ((len=in.read(buff))!=-1){  
    29.                 out.write(buff,0,len);  
    30.             }  
    31.         } catch (IOException e) {  
    32.             e.printStackTrace();  
    33.         } finally {  
    34.             try {  
    35.                 if (in != null){  
    36.                     in.close();  
    37.                 }  
    38.                 if (out != null){  
    39.                     out.close();  
    40.                 }  
    41.             } catch (IOException e) {  
    42.                 e.printStackTrace();  
    43.             }  
    44.         }  
    45.     }  
    46. }  


    3.字符流

        ·两个顶层父抽象类及其实现类

             ·Reader:for reading character streams

                  ··InputStreamReader:从字节流到字符流的桥梁:读取字节流然后按指定的编码方式进行解码(看不懂→能看懂)

                             构造函数要和输入流InputStream/编码方式Charset相关联:System.in/FileInputStream传入

                              ——read()    :读入一个字符

                              ——read(char [] cbuf,int offset,int length)

                              ——close()

                        ···FileReader:读字符文件的方便类,本质是InputStreamReader在构造时 指定了默认的编码方式,用于读取字符流

                                 构造函数要和文件相关联

                  ★InputStreamReader 接收键盘上输入的数据,写入文件中(中文会乱码)

    1. import java.io.*;  
    2.   
    3. /** 
    4.  * Created by 111 on 2016/2/25. 
    5.  */  
    6. public class Demo4 {  
    7.     /** 
    8.      * 控制台输入,写到文件夹中 
    9.      * @param args 
    10.      */  
    11.     public static void main(String [] args){  
    12.         File file = new File("d:/helloWorld.txt");//会覆盖之前的数据  
    13.         OutputStream out = null;  
    14.         InputStreamReader reader = null;  
    15.         try {  
    16.             reader = new InputStreamReader(System.in);  
    17.             out = new FileOutputStream(file);  
    18.             int len = 0;  
    19.             while ((len = reader.read())!= -1){  
    20.                 out.write(len);  
    21.             }  
    22.         } catch (IOException e) {  
    23.             e.printStackTrace();  
    24.         } finally {  
    25.             if (out!=null){  
    26.                 try {  
    27.                     out.close();  
    28.                 } catch (IOException e) {  
    29.                     e.printStackTrace();  
    30.                 }  
    31.             }  
    32.             if (reader!=null){  
    33.                 try {  
    34.                     reader.close();  
    35.                 } catch (IOException e) {  
    36.                     e.printStackTrace();  
    37.                 }  
    38.             }  
    39.         }  
    40.   
    41.     }  
    42. }  


              ··BufferedReader:从一个字符输入(character-input)流中读取文本(text),并进行缓冲字符,默认缓存8192(8M),行最长80

                     构造函数要和Reader in/int size 关联:InputStreamReader

                     ——in read()

                     ——in read(char [] cbuf,int off,int len)

                     ——String readLine()

                     ——close()

                       ★键盘录入,使用缓存

    1. BufferedReader buffr = new BufferedReader(new InputStreamReader(System.in))  



          ·Writer:for writing to character streams (字符流的写操作基本上后面都需要进行flush()操作)

                 ··OutputStreamWriter :从字符流到字节流的桥梁:写出的字符被用指定的编码方式进行编码。

                       构造函数要和OutputStream out/charset 关联:System.out/FileOutputStream

                       ——write(int c):写一个单独的字符

                       ——write(char [] cbuf,int off,int len)

                       ——write(String str,int off,int len)

                       ——flush():刷新流

                       ——close()

                       ···FileWriter:写字符文件的方便类,实质是:OutputStreamWriter指定了默认的本机编码方式,且可以处理文件

                  ··BufferedWriter:写文本到一个字符输出(character-out)流,并对传入的字符进行缓存

                        构造函数要和 Writer out/int size 相关联

                         ——write(int c):写一个单独的字符

                         ——write(char [] cbuf,int off,int len)

                         ——write(String str,int off,int len)

                         ——newLine():换行

                         ——flush():刷新流

                         ——close()

                        ★控制台输出,使用缓存

    1. BufferedWriter buffw= new BufferedWriter(new OutputStreamWriter(System.out,"utf-8"));  


                       ★键盘输入,控制台输出功能

    1. import java.io.*;  
    2.   
    3. /** 
    4.  * Created by 111 on 2016/2/26. 
    5.  */  
    6. public class Demo5 {  
    7.     /** 
    8.      * 键盘输入,控制台输出 
    9.      * @param args 
    10.      */  
    11.     public static void main(String[]args){  
    12.        
    13.         BufferedReader buff = null;  
    14.         BufferedWriter bufferedWriter = null;  
    15.         String line = null;  
    16.         try {  
    17.             buff = new BufferedReader(new InputStreamReader(System.in,"utf-8"));  
    18.             bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out,"utf-8"));  
    19.             <span style="font-family:SimSun;">while</span> ((line=buff.readLine())!=null){  
    20.                 bufferedWriter.write(line);  
    21. <span style="font-family:KaiTi_GB2312;">            <span style="font-family:SimSun;"> }</span></span>  
    22.            bufferedWriter.flush();         //一定要刷新  
    23.         } catch (IOException e) {  
    24.             e.printStackTrace();  
    25.         } finally {  
    26.             if (buff!=null){  
    27.                 try {  
    28.                     buff.close();  
    29.                 } catch (IOException e) {  
    30.                     e.printStackTrace();  
    31.                 }  
    32.             }  
    33.             if (out!=null){  
    34.                 try {  
    35.                     out.close();  
    36.                 } catch (IOException e) {  
    37.                     e.printStackTrace();  
    38.                 }  
    39.             }  
    40.         }  
    41.   
    42.     }  
    43. }  


    ☆面试题:简述一下将文件中的数据输入到另一个文件中的步骤

             1.首先创建File对象,并且和需要操作的文件相关联,这时候需要对文件进行判断是否存在,不存在则会报错

             2.既然是读取文件并且写到文件,属于纯文本,可以选择FileReader和FileWriter进行读写操作,如果出现乱码可以使用其父类指定编码方式

             3.创建FileReader对象用于读取文件中的数据,这里可以使用缓冲流进行处理,提高效率,创建一个BufferedReader对象

                   BufferedReader buffr = new BufferedReader(new InputStreamReader(new FileReader(file)));

            4.创建FileWriter,同上使用缓存

             ★代码如下

    1. import java.io.*;  
    2.   
    3. /** 
    4.  * Created by 111 on 2016/2/26. 
    5.  */  
    6. public class Demo6 {  
    7.     public static void main(String[] args){  
    8.         File origin = new File("d:/helloWorld.txt");  
    9.         File destination = new File("d:/helloWorld6.txt");  
    10.         InputStreamReader in = null;  
    11.         OutputStreamWriter out = null;  
    12.         BufferedReader reader = null;  
    13.         BufferedWriter writer = null;  
    14.         if (!origin.exists()){  
    15.             try {  
    16.                 origin.createNewFile();  
    17.             } catch (IOException e) {  
    18.                 e.printStackTrace();  
    19.             }  
    20.         }  
    21.         try {  
    22.             reader = new BufferedReader(new InputStreamReader(new FileInputStream(origin),"ISO-8859-1"));  
    23. //            reader = new BufferedReader(new FileReader(origin));  
    24.             writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destination),"ISO-8859-1"));  
    25.             String line = null;  
    26.             while ((line = reader.readLine())!=null){  
    27.                 writer.write(line);  
    28.                 writer.newLine();  
    29.             }  
    30.             writer.flush();  
    31.         } catch (IOException e) {  
    32.             e.printStackTrace();  
    33.         } finally {  
    34.             if (in!=null){  
    35.                 try {  
    36.                     in.close();  
    37.                 } catch (IOException e) {  
    38.                     e.printStackTrace();  
    39.                 }  
    40.             }  
    41.             if (out!=null){  
    42.                 try {  
    43.                     out.close();  
    44.                 } catch (IOException e) {  
    45.                     e.printStackTrace();  
    46.                 }  
    47.             }  
    48.             if (reader!= null){  
    49.                 try {  
    50.                     reader.close();  
    51.                 } catch (IOException e) {  
    52.                     e.printStackTrace();  
    53.                 }  
    54.             }  
    55.             if (writer!=null){  
    56.                 try {  
    57.                     writer.close();  
    58.                 } catch (IOException e) {  
    59.                     e.printStackTrace();  
    60.                 }  
    61.             }  
    62.         }  
    63.     }  
    64. }  


  • 相关阅读:
    HTML5
    PHP
    eclipse项目导入到android studio
    Jpush教材
    Android性能优化典范
    Fresco好案例
    扫二维码关注微信号,回复“送礼包”就送超值大礼!
    Android开源项目大全之工具库
    android学习“知乎”建议
    C# Json时间类型的转换
  • 原文地址:https://www.cnblogs.com/esther-qing/p/6483613.html
Copyright © 2020-2023  润新知