2017-05-27 179 views
0

我是Android编程的初学者。 我想提供一个窗体给用户输入一些信息。 我想将该信息写入文件,然后从文件中读取并在TextView中显示。目前,我读到的是null。你能帮我解决这个问题吗? 的代码是这一个:Android - 从文件读取和写入

submit.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     // write 
     StringBuilder s = new StringBuilder(); 
     s.append("Event name: " + editText1.getText() + "|"); 
     s.append("Date: " + editText2.getText() + "|"); 
     s.append("Details: " + editText3.getText() + "|"); 

     String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); 
     File file= new File(extStorageDirectory, "config.txt"); 
     try { 
      writeToFile(s.toString().getBytes(), file); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     // read from file and show in text view 
     Context context = getApplicationContext(); 
     String filename = "config.txt"; 
     String str = readFromFile(context, filename); 
     String first = "You have inputted: \n"; 
     first += str; 
     textView.setText(first); 

    } 
}); 

写功能:

public static void writeToFile(byte[] data, File file) throws IOException { 
    BufferedOutputStream bos = null; 
    try { 
     FileOutputStream fos = new FileOutputStream(file); 
     bos = new BufferedOutputStream(fos); 
     bos.write(data); 
    } 
    finally { 
     if (bos != null) { 
      try { 
       bos.flush(); 
       bos.close(); 
      } 
      catch (Exception e) { 
      } 
     } 
    } 
} 

读取功能:

public String readFromFile(Context context, String filename) { 
    try { 
     FileInputStream fis = context.openFileInput(filename); 
     InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); 
     BufferedReader bufferedReader = new BufferedReader(isr); 
     StringBuilder sb = new StringBuilder(); 
     String line; 
     while ((line = bufferedReader.readLine()) != null) { 
      sb.append(line).append("\n"); 
     } 
     return sb.toString(); 
    } catch (FileNotFoundException e) { 
     return ""; 
    } catch (UnsupportedEncodingException e) { 
     return ""; 
    } catch (IOException e) { 
     return ""; 
    } 
} 
+0

您确定您使用正确的文件路径吗? –

+0

如果我没有,我会有一个错误。但我没有错误也没有警告 –

回答

0

EDITTEXT的getText()方法返回editable。所以首先你应该使用toString()函数将它转换为字符串。还要检查你是否给了WRITE_EXTERNAL_STORAGE权限。

+1

谢谢你的回答! –

0

如果我不想你写入文件

String extStorageDirectory = 
Environment.getExternalStorageDirectory().toString(); 
File file= new File(extStorageDirectory, "config.txt"); 
东西

但你读过从

FileInputStream fis = context.openFileInput(filename); 

后者在应用程序基目录中使用了一个dir,而输出则转到了外部strage目录的基本目录。

为什么不使用context.openFileOutput()代替getExternalStorageDirectory()

如果该文件应该被存储在外部,尝试如下:您创建File对象的方式保持不变。请用FileInputStream代替FileOutputStream fos = new FileOutputStream(file);(写作)。请记住在清单中设置适当的权限。在什么条件下他们是必要的,请参阅Android文档。

+0

我怎么才能从外部存储读取? –

+0

我已经设法使用内部存储。谢谢托马斯! –

+0

很高兴如果我能够帮助 – Thomas