使用 OuputStreamWriter 时的异常



当使用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;
    }
}

试试这个

 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()"

编辑2:确保有权写入文件。您应该在清单文件中包含此内容

相关内容

  • 没有找到相关文章

最新更新