【问题标题】:exception while using OuputStreamWriter使用 OutputStreamWriter 时出现异常
【发布时间】:2016-11-08 14:28:04
【问题描述】:

在使用 OutputStreamWriter 时,当我尝试创建多个目录(取决于函数结果)并将字符串写入文件时,我遇到了一个异常。

为什么我的程序总是跳到异常并且 saveFile() 总是返回 false?

 private boolean saveFile() {

    File card = Environment.getExternalStorageDirectory();
    File dir = new File(card.getAbsolutePath() + choosePath());
    if (!dir.exists()) {
        dir.mkdir();// creates directory by the given pathname
    }
    File file = new File(dir, etFileName.getText().toString());
    try {
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        osw.write(configString); // from character to byte
        osw.flush();
        osw.close();
        return true;
    } catch (IOException e) {
        return false;
    }
}

【问题讨论】:

  • 尝试在调试中执行该代码,以便您了解哪一行失败
  • FileOutputStream fos = new FileOutputStream(file); // 我认为这一行,我不能在模拟器上很好地调试,因为我需要我的目录。我遇到了致命的崩溃,但据我所知,当我点击保存时它返回一个错误,当我尝试查看我的文件列表时它只是崩溃了。在这一行中,它在调试器空指针异常中说,这是奇怪的尝试调试整个早上都没有结果
  • 文件是否为空?
  • etFileName.getText() 返回一些值?
  • 不,我用吐司检查了 etFileName,它会返回我在文本字段中写的任何文本

标签: android file android-studio directory outputstream


【解决方案1】:

试试这个

 private boolean saveFile() {

    File card = Environment.getExternalStorageDirectory();
    String fullPath = card.getAbsolutePath() 
        + choosePath()
        + etFileName.getText().toString(); //I guess this should generate the fullPath, if i understood well your code
    File file = new File(fullPath); //open the file
    file.getParentFile().mkdirs(); //create parent dirs if necessary
    // if file doesn't exists, then create it
    if (!file.exists()) {
        file.createNewFile();
    }
    try {
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        osw.write(configString); // from character to byte
        osw.flush();
        osw.close();
        return true;
    } catch (IOException e) {
        return false;
    }
}

编辑 1:添加“file.createNewFile()”

EDIT 2:一定要有写文件的权限。你应该在清单文件中有这个

【讨论】:

  • 不幸的是,同样的问题仍然存在!!!好主意,我自己玩了一段时间 mkdirs() 。但保存文件仍然返回 false 并且不会将任何新文件保存到目录中
  • 我有一个完美运行的加载文件。这就是让这变得如此烦人的原因!
  • 我的回答中哪一行失败了?哪些变量最终为空?
  • 文件 file = new File(fullPath); //打开文件这没关系我得到文件:....不是空的!但是,这一行失败 FileOutputStream fos = new FileOutputStream(file);
  • 好像文件不是 FileOutPutStream 的正确参数!从这里它跳转到异常,这正是它与我的代码一起工作的方式。我还尝试了 Bufferedwriter 并没有变得更好。虽然我承认我不知道我在做什么只是做了 Bufferedreader 的修订
猜你喜欢
  • 2011-10-15
  • 2015-02-05
  • 2014-08-06
  • 1970-01-01
  • 2011-09-15
  • 2011-08-11
  • 2011-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多