android文件寫入和讀取
阿新 • • 發佈:2018-12-20
led output cat put color write efi 數組 text
//讀寫文件函數調用
writeFileData(filename,datas); String result=readFileData(filename); Toast.makeText(Main2Activity.this,result.getClass().toString(),Toast.LENGTH_SHORT).show();
下面是讀寫代碼的實現:
//文件寫入 public void writeFileData(String filename, String content){ try { FileOutputStream fos = this.openFileOutput(filename, MODE_PRIVATE);//獲得FileOutputStream //將要寫入的字符串轉換為byte數組 byte[] bytes = content.getBytes(); fos.write(bytes);//將byte數組寫入文件 fos.close();//關閉文件輸出流 } catch (Exception e) { e.printStackTrace(); } } //文件讀取public String readFileData(String fileName){ String result=""; try{ FileInputStream fis = openFileInput(fileName); //獲取文件長度 int lenght = fis.available(); byte[] buffer = new byte[lenght]; fis.read(buffer); //將byte數組轉換成指定格式的字符串result = new String(buffer, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return result; }
android文件寫入和讀取