Android Studio2.3.3写入文件

时间:2017-08-05 13:31:44

标签: android

我创建了一个文件并使用editText写入文件。现在我想写入一个名为" note.txt"的文件。但要写入的内容应存储在变量中。任何人都可以帮我处理代码吗?

2 个答案:

答案 0 :(得分:0)

private void writeFile() {

   File extStore = Environment.getExternalStorageDirectory();
   // ==> /storage/emulated/0/note.txt
   String path = extStore.getAbsolutePath() + "/" + fileName;
   Log.i("ExternalStorageDemo", "Save to: " + path);

   String data = editText.getText().toString();

   try {
       File myFile = new File(path);
       myFile.createNewFile();
       FileOutputStream fOut = new FileOutputStream(myFile);
       OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
       myOutWriter.append(data);
       myOutWriter.close();
       fOut.close();

       Toast.makeText(getApplicationContext(), fileName + " saved", Toast.LENGTH_LONG).show();
   } catch (Exception e) {
       e.printStackTrace();
   }

}

答案 1 :(得分:0)

你是说这个吗?:

private void save(String inputText) {
    FileOutputStream out = null;
    BufferedWriter writer = null;
    try{
        out = openFileOutput("note.txt",Context.MODE_PRIVATE);
        writer = new BufferedWriter(new OutputStreamWriter(out));
        writer.write(inputText);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try{
            if (writer!=null);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}