FileWriter只能接受字符串形式的參數,也就是說只能把內容存到文本文件。相對於文本文
件,採用二進制格式的文件存儲更省空間spa
InputStream用於按字節從輸入流讀取數據。其中的int read()方法讀取一個字節,這個字節
以整數形式返回0到255之間的一個值。爲何讀一個字節,而不直接返回一個byte類型的值?
由於byte類型最高位是符號位,它所能表示的最大的正整數是127。code
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用於按字節把數
據寫到文件。例如,按字節把內容從一個文件讀出來,並寫入另一個新文件,也就是文件復
制功能。blog
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()方法能夠建立多級目錄。例如,當一個目錄不存在時,就建立它。get
File tempDir = new File(imgPath); if(!tempDir.exists()){ tempDir.mkdirs(); }