【问题标题】:File is created with no data is written to it创建文件时未写入任何数据
【发布时间】:2012-09-08 08:07:50
【问题描述】:

我尝试使用如下所示的代码创建一个文本文件并向其中写入数据:

JAVA CODE_1:

File dir = Environment.getExternalStorageDirectory();
    File file = new File(dir,"/DCIM/"+fileTitle);

    try {           
        if( file.exists() ){
        FileOutputStream fos = openFileOutput(fileTitle, MODE_WORLD_READABLE);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        osw.write("this is a text");
        osw.flush();
        osw.close();
        } else {
            file.createNewFile();
            FileOutputStream fos = openFileOutput(fileTitle, MODE_WORLD_READABLE);
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            osw.write("this is a text");
            osw.flush();
            osw.close();
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

但是当我检查 DCIM 目录时,我发现文件已创建但没有数据写入其中。请告诉我我的错误在哪里。

【问题讨论】:

标签: android file-io outputstream


【解决方案1】:

抱歉,它不是在外部存储上创建的,而是在应用程序的内部存储上创建的, (检查您的文件是在/data/data/<Application_Package_Name>/files 目录上创建的)

因为,

您正在使用openFileOutput 在应用程序的内部存储中创建文件。

public abstract FileOutputStream openFileOutput (String name, int mode)

自:API 级别 1

打开与此上下文的应用程序包关联的私有文件以进行写入。如果文件尚不存在,则创建该文件。

代码:

file.createNewFile();
FileOutputStream fos = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write("this is a text");
osw.flush();
osw.close();

【讨论】:

  • 但该文件存在于 ../DCIM/ 目录下..我没有像你在我的设备中发布的那样的 pth
  • 查看 adb shell... 你得到了文件路径和文件。它也可用于 DCIM 文件夹,因为您正在使用此代码行 file.createNewFile(); 创建空文件
  • 但很抱歉给您带来不便,我不知道如何检查您发布的路径..我没有这样的路径
  • 或者至少请让我知道如何在 DCIM 下正确创建文本文件并将数据添加到该文件
  • 我把它改成了 fos = FileOutPutStream(fileTitle,MOODE_WORLD_READABLE);但eclipse用红色强调文件输出流
【解决方案2】:

仅供参考

        FileOutputStream fos = openFileOutput(fileTitle, MODE_WORLD_READABLE);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        osw.write("this is a text");
        osw.flush();
        osw.close();

它将在内部存储中创建文件。

或者使用

        File dir = Environment.getExternalStorageDirectory();
        File file = new File(dir,"/DCIM/"+fileTitle);
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        osw.write("this is a text");
        osw.flush();
        osw.close();

【讨论】:

  • 第一个代码 sn-p 我已经使用过它,它只是创建文件,没有数据写入。关于第二个代码 sn -p eclipse 用红色下划线 FileOutputStream
  • 关于第二个代码没有错误但文件仍然是空的
猜你喜欢
  • 1970-01-01
  • 2019-02-21
  • 2019-12-05
  • 2015-07-21
  • 1970-01-01
  • 2020-06-13
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
相关资源
最近更新 更多