Java I/O流InputStream,OutputStream,Reader,Writer

pan_jinquan發表於2016-07-23

Java流總結

原文地址:http://blog.csdn.net/oypj2010/article/details/7660150 一、  流的分類 – 輸入流:只能從中讀取位元組資料,而不能向其寫出資料 – 輸出流:只能向其寫入位元組資料,而不能從中讀取資料 •   按照流所處理的資料型別 – 位元組流:用於處理位元組資料。 – 字元流:用於處理Unicode字元資料。 •   按照流所處理的源 – 節點流:從/向一個特定的IO裝置讀/寫資料的流。(低階流) – 處理流:對已存在的流進行連線和封裝的流。(高階流) 二、  緩衝流 衝的功能,提高了讀寫的效率,同時增加了一些新的方法。 •  J2SDK提供了四種快取流: – BufferedReader – BufferedWriter – BufferedInputStream s – BufferedOutputStream – mark()用於“標記”當前位置,就像加入了一個書籤,可以使用reset()方法返回這個標記重新讀取資料。 •  BufferedReader提供了readLine()方法用於讀取一行字串(以\r或\n分隔)。 •  BufferedWriter提供了newLine()用於寫入一個行分隔符。 •  對於輸出的緩衝流,寫出的資料會先在記憶體中快取,使用flush()方法將會使記憶體中的資料立刻寫出。 三、  類層次 3.1、InputStream類層次   3.2、OutputStream類層次 3.3、Reader類層次   3.4、Writer類層次 四、  常用的字元流與位元組流的轉化 說明: 1.     位元組流用於讀寫諸如影像資料之類的原始位元組流。 2.     字元流用於讀寫諸如檔案資料之類的字元流。 3.     低階流能和外設交流。 4.     高階流能提高效率。 5. InputStreamReader 是位元組流通向字元流的橋樑。 6. OutputStreamWriter是字元流通向位元組流的橋樑。 五、  程式碼例項 5.1、常用讀檔案:
/**
     *以位元組為單位讀取檔案,常用於讀二進位制檔案,如圖片、聲音、影像等檔案。
     *@paramfileName:檔案的名
     */
    publicstaticvoid readFileByBytes(String fileName) {
       File file= new File(fileName);
       InputStream in = null;
       try {
           logger.debug("以位元組為單位讀取檔案內容,一次讀多個位元組:");
            /*一次讀多個位元組*/
           byte[] tempbytes =newbyte[100];
           int byteread = 0;
           in = new FileInputStream(file);
            /*讀入多個位元組到位元組陣列中,byteread為一次讀入的位元組數*/
           while ((byteread = in.read(tempbytes)) != -1) {
              logger.debug(tempbytes);
              logger.debug(0);
              logger.debug(byteread);
           }
       } catch (Exception e1) {
           logger.error("讀取文字檔案異常",e1);
       } finally {
           if (in !=null) {
              try {
                  in.close();
              } catch (IOException e1) {
                  logger.error("讀取文字檔案異常",e1);
              }
           }
       }
    }
/**
     *以字元為單位讀取檔案,常用於讀文字,數字等型別的檔案
     *@paramfileName:檔名
     */
    public staticvoid readFileByChars(StringfileName) {
       Reader reader = null;
       try {
           logger.debug("以字元為單位讀取檔案內容,一次讀多個位元組:");
            /*一次讀多個字元*/
           char[] tempchars =newchar[100];
           int charread = 0;
           if(fileName!=null&&!"".equals(fileName)){
              reader = new InputStreamReader(new FileInputStream(fileName));
               /*讀入多個字元到字元陣列中,charread為一次讀取字元數*/
              while ((charread = reader.read(tempchars)) != -1) {
                   /*對於windows下,rn這兩個字元在一起時,表示一個換行。*/
                   /*但如果這兩個字元分開顯示時,會換兩次行。*/
                   /*因此,遮蔽掉r,或者遮蔽n。否則,將會多出很多空行。*/
                  if ((charread == tempchars.length)
                         && (tempchars[tempchars.length - 1] !='r')) {
                     logger.debug(tempchars);
                  } else {
                     for (int i = 0; i < charread; i++) {
                         if (tempchars[i] =='r') {
                            continue;
                         } else {
                            logger.debug(tempchars[i]);
                         }
                     }
                  }
              }
           }
       } catch (Exception e1) {
           logger.error("讀取文字檔案異常",e1);
       } finally {
           if (reader !=null) {
              try {
                  reader.close();
              } catch (IOException e1) {
                  logger.error("讀取文字檔案異常",e1);
              }
           }
       }
    }
 
/**
     *以行為單位讀取檔案,常用於讀面向行的格式化檔案
     *@paramfileName:檔名
     */
    publicstatic List<String> readFileByLines(StringfileName) {
       List<String> list = new ArrayList<String>();
       if(fileName!=null&&!"".equals(fileName)){
       File file = new File(fileName);
       BufferedReader reader = null;
       try {
           logger.debug("以行為單位讀取檔案內容,一次讀一整行:");
           reader = new BufferedReader(new FileReader(file));
           String tempString = null;
            /*一次讀入一行,直到讀入null為檔案結束*/
           while ((tempString = reader.readLine()) !=null) {
              logger.debug(tempString);
              list.add(tempString);
           }
       } catch (IOException e) {
           logger.error("讀取文字檔案異常",e);
       } finally {
           if (reader !=null) {
              try {
                  reader.close();
              } catch (IOException e1) {
                  logger.error("讀取文字檔案異常",e1);
              }
           }
       }
    }
       return list;
    }
 
5.2、常用寫檔案:
/** 
    *把內容寫到檔案
    *@paramfilePathName檔名 
    *@paramList<String>檔案內容 
    */ 
    publicstaticboolean writerFile(String filePathName,String content){
       boolean flag=false;
       OutputStreamWriter osw=null;
       try {
           if(filePathName!=null&&!"".equals(filePathName)){
              osw = new OutputStreamWriter(new FileOutputStream(filePathName));
           }
       } catch (FileNotFoundException e1) {
           flag=false;
           e1.printStackTrace();
       }
       if(osw!=null){
       BufferedWriter bw=new BufferedWriter(osw);
       try {
           if(content!=null&&!"".equals(content)){
              bw.write(content);
              flag= true;
           }
       } catch (IOException e) {
           flag=false;
           e.printStackTrace();
       }finally{
           try {
              bw.close();
              osw.close();
           } catch (IOException e) {
              flag=false;
              e.printStackTrace();
           }         
       }
       }
       return flag;
    }
 
 
/** 
    *把內容寫到檔案或追加到檔案中
    *@paramfilePathName檔名 
    *@paramList<String>檔案內容 
    */ 
    publicstaticboolean writerFileIsAppend(String filePathName,String content){
       boolean flag=false;
       OutputStreamWriter osw=null;
       try {
           if (filePathName!=null&&!"".equals(filePathName)) {
              osw = new OutputStreamWriter(new FileOutputStream(filePathName,true));
           }
       } catch (Exception e1) {
           flag=false;
           e1.printStackTrace();
       }
       if(osw!=null){
       BufferedWriter bw=new BufferedWriter(osw);
       try {
           if(content!=null&&!"".equals(content)){
              bw.write(content);
              flag= true;
           }
       } catch (IOException e) {
           flag=false;
           e.printStackTrace();
       }finally{
           try {
              bw.close();
              osw.close();
           } catch (IOException e) {
              flag=false;
              e.printStackTrace();
           }         
       }
       }
       return flag;
    }
六、  RandomAccessFile
6.1:說明
•   RandomAccessFile是一種特殊的檔案流,可以用它在檔案的任何地方查詢或者插入資料
•   RandomAccessFile同時實現了DataInput和DataOutput介面,所以可以用它來讀/寫檔案
•   構造器:
---RandomAccessFile(java.io.File f,String mode)
---RandomAccessFile(String file,String mode)
6.2:程式碼示例
/**
     *Description: 讀取檔案最後一行內容
     *@param  fileName檔案路徑名+檔名
     */
    publicstatic String getfinalLineData(StringpathName){
    RandomAccessFileraf = null;
    StringlastLine = "";
       try {
           raf = new RandomAccessFile(pathName,"r");
           long len = raf.length();
           if (len != 0L) {
              long pos = len - 1;
              while (pos > 0) {
                  pos--;
                  raf.seek(pos);
                  if (raf.readByte() =='\n') {
                     lastLine = raf.readLine();
                     break;
                  }
              }
           }
       } catch (Exception e) {
           e.printStackTrace();
       }finally {
            if (raf !=null) {
                try {
                  raf.close();
                } catch (IOException e1) {
                  e1.getStackTrace();
                }
            }
        }
       return lastLine;
    }
七、  注意事項
1、將高階流“套接“在低階流上,這樣起到緩衝的作用可以提高效率。
2、將使用完的流關閉,釋放資源。
3、讀取如圖片、聲音、影像等檔案用位元組流。
4、讀取如文字等檔案用字元流。
5、根據具體的資料格式選擇合適的讀寫方法、如按行讀寫、按照位元組讀寫等。
•   按資料流動方向
•   緩衝流要“套接”在相應的節點流之上,對讀寫的資料提供了緩
•  緩衝輸入流支援其父類的mark()和reset()方法:

相關文章