0

在我的应用程序中有 3 个 EditTexts。我想将此 EditTexts 的内容写入文件,但 filewrite 会引发空指针异常。为什么?

OutputStream f1;是全局声明的。

BtnSave = (Button)findViewById(R.id.Button01);
BtnSave.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        intoarray =   name + "|" + number + "|" + freq + "\n";
        Toast.makeText(Main.this, "" + intoarray, Toast.LENGTH_SHORT).show();
        //so far so good
          byte buf[] = intoarray.getBytes(); 

          try {
            f1 = new FileOutputStream("file2.txt");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
          try {
            f1.write(buf);  //nullpointer exception
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
          try {
            f1.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
4

3 回答 3

0

您当前使用的方式不起作用,通常您正在尝试写入内部存储,这是您的应用程序私有的,并且必须包含在您的应用程序目录中。

创建文件流的正确方法是

fin  = openFileOutput("file2.txt", Context.MODE_PRIVATE); // open for writing
fout = openFileInput("file2.txt", Context.MODE_PRIVATE);  // open for reading 

它将在您的应用程序的存储区域中找到文件,通常类似于

/data/data/com.yourpackagename/files/...

如果您当然需要目录结构,您仍然可以在应用程序区域内创建目录。

如果您需要写入不同进程的外部存储,有关更多信息,请参阅Android 数据存储

于 2011-07-26T00:19:30.247 回答
0

最有可能的

f1 = new FileOutputStream("file2.txt");

失败了,因为你发现了异常 f1 仍然为空。在 Android 中的大多数情况下,您只能在应用程序数据目录或外部存储中创建文件。

于 2011-07-25T22:44:17.340 回答
0

对不起,你试图帮助我,我问错了问题。我想使用内部存储(现在可以使用)。我不知道问题是什么,但是使用下面的代码(我已经使用了很多)文件写入是可以的:

try {
    File root = Environment.getExternalStorageDirectory();
    File file = new File(root, "Data.txt");
    if (root.canWrite()) {
        FileWriter filewriter = new FileWriter(file, true);
        BufferedWriter out = new BufferedWriterfilewriter);
        out.write(intoarray);
        out.close();
    }
} catch (IOException e) {
    Log.e("TAG", "Could not write file " + e.getMessage());
}

如果可以,我会删除该主题。我接受这个答案来结束这个话题。

不管怎么说,还是要谢谢你。

于 2011-09-06T10:08:53.977 回答