1. 程式人生 > >Java如何用WriteUTF寫檔案,ReadUTF讀檔案

Java如何用WriteUTF寫檔案,ReadUTF讀檔案

直接上樣例參考(附有部分說明): File fileName = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + “/test/test.levp”); FileOutputStream fileOutputStream=null; DataOutputStream dataOutputStream=null; try { fileOutputStream = new FileOutputStream(fileName); dataOutputStream = new DataOutputStream(fileOutputStream); dataOutputStream.writeUTF(“第1句話。”); dataOutputStream.writeUTF(“第2句話。”); dataOutputStream.writeUTF(“第3句話。”); dataOutputStream.writeUTF(“第4句話。”); ………………………………………………………………………… dataOutputStream.flush(); fileOutputStream.close(); dataOutputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { fileOutputStream.close(); dataOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } StringBuilder content = new StringBuilder(); FileInputStream fileInputStream = null; DataInputStream dataInputStream = null; try { fileInputStream = new FileInputStream(fileName); dataInputStream = new DataInputStream(fileInputStream); while (true) { content.append(dataInputStream.readUTF()+ “\n”);//by throwing java.io.EOFException to get the Reading result(目前,ReadReadUTFT還沒有現判斷檔案讀完的方法,可通過檔案讀到底發生異常來處理相關資料或目的) } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace();//探測發生檔案讀完的異常後,程式跳轉至此處進行處理(也可以在處設定相關目的碼),最後跳轉finally處 } finally { tv_Sample.setText(content);//實現如在設定的TextView中顯示等目的 try { fileInputStream.close(); dataInputStream.close(); } catch (IOException e) { e.printStackTrace(); } }