java 文件讀寫工具 FileUtil


代碼如下:

  1 package com.wiscom.utils;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileNotFoundException;
  7 import java.io.FileWriter;
  8 import java.io.IOException;
  9 import java.io.InputStream;
 10 import java.io.InputStreamReader;
 11 import java.io.Reader;
 12 import java.io.UnsupportedEncodingException;
 13 
 14 public class FileUtil {
 15     
 16     /**
 17      *  以字節為單位讀取文件,通常用於讀取二進制文件,如圖片
 18      * @param path
 19      * @return
 20      */
 21     public static String readByBytes(String path) {    
 22         String content = null;
 23         
 24         try {
 25             InputStream inputStream = new FileInputStream(path);
 26             StringBuffer sb = new StringBuffer();
 27             int c = 0;
 28             byte[] bytes = new byte[1024];
 29             /*
 30              * InputStream.read(byte[] b)
 31              * 
 32              * Reads some number of bytes from the input stream and stores them into the buffer array b. 從輸入流中讀取一些字節存入緩沖數組b中
 33              * The number of bytes actually read is returned as an integer.  返回實際讀到的字節數
 34              * This method blocks until input data is available, end of file is detected, or an exception is thrown. 
 35              * 該方法會一直阻塞,直到輸入數據可以得到、或檢測到文件結束、或拋出異常  -- 意思是得到數據就返回
 36              */
 37             while ((c = inputStream.read(bytes)) != -1) {
 38                 sb.append(new String(bytes, 0, c, "utf-8"));
 39             }
 40             
 41             content = sb.toString();
 42             inputStream.close();
 43         } catch (FileNotFoundException e) {
 44             e.printStackTrace();
 45         } catch (IOException e) {
 46             e.printStackTrace();
 47         }
 48         
 49         return content;
 50     } 
 51     
 52     /**
 53      *  以行為單位讀取文件,常用於讀取面向行的格式化文件
 54      * @param path
 55      * @return
 56      */
 57     public static String readByLines(String path) {
 58         String content = null;
 59         
 60         
 61         try {
 62             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "utf-8"));
 63             
 64             StringBuffer sb = new StringBuffer();
 65             String temp = null;
 66             while ((temp = bufferedReader.readLine()) != null) {
 67                 sb.append(temp);
 68             }
 69             
 70             content = sb.toString();
 71             bufferedReader.close();
 72         } catch (UnsupportedEncodingException  e) {
 73             e.printStackTrace();
 74         } catch (IOException e) {
 75             e.printStackTrace();
 76         }
 77         
 78         return content;
 79     }
 80     
 81     /**
 82      *  以字符為單位讀取文件,常用於讀取文本文件
 83      * @param path
 84      * @return
 85      */
 86     public static String readByChars(String path) {
 87         String content = null;
 88         
 89         try {
 90             
 91             Reader reader = new InputStreamReader(new FileInputStream(path), "utf-8");
 92             StringBuffer sb = new StringBuffer();
 93             
 94 
 95             char[] tempchars = new char[1024];
 96             while (reader.read(tempchars) != -1) {
 97                 sb.append(tempchars);
 98             }
 99             
100             content = sb.toString();
101             reader.close();    
102         } catch (Exception e) {
103             e.printStackTrace();
104         }    
105         return content;
106     }
107     
108     /**
109      *  把內容content寫的path文件中
110      * @param content
111      * @param path
112      * @return
113      */
114     public static boolean saveAs(String content, String path) {
115         
116         FileWriter fw = null;
117         
118         //System.out.println("把內容:" + content + ", 寫入文件:"  + path);
119         
120         try {
121             /**
122              * Constructs a FileWriter object given a File object. 
123              * If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
124              * 根據給定的File對象構造一個FileWriter對象。 如果append參數為true, 則字節將被寫入到文件的末尾(向文件中追加內容)
125              *
126              *    Parameters:
127              *        file,  a File object to write to 帶寫入的文件對象
128              *        append,  if true, then bytes will be written to the end of the file rather than the beginning
129              *    Throws:
130              *        IOException - 
131              *        if the file exists but is a directory rather than a regular file, 
132              *            does not exist but cannot be created, 
133              *            or cannot be opened for any other reason
134              *      報異常的3種情況:
135              *          file對象是一個存在的目錄(不是一個常規文件)
136              *          file對象是一個不存在的常規文件,但不能被創建
137              *          file對象是一個存在的常規文件,但不能被打開
138              *
139              */
140             fw = new FileWriter(new File(path), false);
141             if (content != null) {
142                 fw.write(content);
143             }    
144         } catch (IOException e) {
145             e.printStackTrace();
146             return false;
147         } finally {
148             if (fw != null) {
149                 try {
150                     fw.flush();
151                     fw.close();
152                 } catch (IOException e) {
153                     e.printStackTrace();
154                 }
155             }
156         }
157         return true;
158     }
159 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM