android中的檔案儲存
阿新 • • 發佈:2019-01-28
使用FileInputStream和FileOutputStream的物件呼叫方法來建立
將資料寫入手機記憶體
public class HandFile { private Context context; public HandFile(Context context) { this.context = context; } public void writeFileData(String filename,String message){ try { FileOutputStream fileOutputStream =context自己建立 的HandFile類.openFileOutput(filename,context.MODE_PRIVATE); byte[] bytes=message.getBytes(); fileOutputStream.write(bytes); fileOutputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public String readFileData(String fileName){ String result=""; FileInputStream fileInputStream = null; try { fileInputStream = context.openFileInput(fileName); int length=fileInputStream.available(); byte[] bytes=new byte[length]; fileInputStream.read(bytes); result=new String(bytes);fileInputStream.close(); } catch (Exception e) { e.printStackTrace(); } return result; } }
public class MainActivity extends AppCompatActivity { private TextView mtv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String message="emmmm……我就是傳說中的資料,嘻嘻嘻。我特麼學android好累啊," + "可是又有什麼辦法呢,誰讓我大一大二兩年太放縱了呢,現在學點東西不至於找不到工作吧," + "考研也很累啊,下雪了,我的書還能到嗎……"; HandFile handFile=new HandFile(this); handFile.writeFileData("first",message); String result=handFile.readFileData("first"); mtv= (TextView) findViewById(R.id.file); mtv.setText(result); } }將message的內容存入TextView。