標籤:二進位 txt test 異常 public 空間 targe exception 關閉
FileWriter只能接受字串形式的參數,也就是說只能把內容存到文字檔。相對於文本文
件,採用二進位格式的檔案儲存體更省空間
InputStream用於按位元組從輸入資料流讀取資料。其中的int read()方法讀取一個位元組,這個位元組
以整數形式返回0到255之間的一個值。為什麼讀一個位元組,而不直接返回一個byte類型的值?
因為byte類型最高位是符號位,它所能表示的最大的正整數是127。
InputStream只是一個抽象類別,不能執行個體化。FilelnputStream是InputStream的子類,用於從
檔案中按位元組讀取。
public static void main(String[] args) throws IOException { String filePath = "d:/test.txt"; File file = new File (filePath); //根據檔案路徑建立一個檔案對象 //如果找不到檔案,會拋出FileNotFoundException異常 FilelnputStream filelnput = new FilelnputStream(file);} filelnput.close (); //關閉檔案輸入資料流,如果無法正常關閉,會拋出IOException異常
OutputStream中的write(int b)方法用於按位元組寫出資料。FileOutputStream用於按位元組把數
據寫到檔案。例如,按位元組把內容從一個檔案讀出來,並寫入另外一個新檔案,也就是檔案複
制功能。
File fileln = new File ("source. txt"); //開啟源檔案File fileOut = new File ("target.txt”); //開啟寫入檔案,也就是目標檔案FilelnputStream streamln = new FilelnputStream (fileln); //根據源檔案構建輸入資料流FileOutputStream streamOut = new FileOutputStream (fileOut); //根據目標檔案構建輸出資料流int c;//從源檔案中按位元組讀入資料,如果內容還沒讀完,則繼續while ((c = streamln.read()) != -1) {streamOut .write (c); //寫入目標檔案}streamln.close。; //關閉輸入資料流streamOut.close(); //關閉輸出資料流
判斷檔案是否已經存在,如果不存在則產生這個檔案。
File dataFile = new File(dicDir + dataDic);if (!dataFile.exists()) {//如果檔案不存在則寫入檔案}
用File.mkdirs()方法可以建立多級目錄。例如,當一個目錄不存在時,就建立它。
File tempDir = new File(imgPath);if(!tempDir.exists()){tempDir.mkdirs();}
java讀取檔案:二進位檔案