非法参数异常:文件包含路径分隔符 Android

6

我正在尝试在我的HTC One上写入输出文件,并在LogCat中获得以下消息:

11-21 08:05:18.228: W/System.err(6609): java.lang.IllegalArgumentException: 文件/storage/emulated/0/com.example.pattern1/myfile.txt包含路径分隔符

下面是源代码:

    protected void writeToFile(String string){

    File patternDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/com.example.pattern1/myfile.txt");
    patternDirectory.mkdirs();

    FileOutputStream outputStream;

    try {
      outputStream = openFileOutput(patternDirectory.getAbsolutePath().toString(), Context.MODE_APPEND);
      outputStream.write(string.getBytes());
      TextView t = (TextView)findViewById(R.id.bottomMidText);
      t.setText(patternDirectory.getAbsolutePath().toString());
      outputStream.close();

    } catch (Exception e) {
      e.printStackTrace();
    }

我希望有人能够帮忙确认问题所在。

@Talal Saleem,哪一行代码出错了? - Kick Buttowski
1
@timrau,您的链接是输入案例,这是有关输出的问题。只是小问题,我知道。 - William T. Mallard
2个回答

20

openFileInput方法不接受路径分隔符('/')。

它仅接受您要打开/访问的文件名称。因此,请更改语句。

outputStream = openFileOutput(patternDirectory.getAbsolutePath().toString(), Context.MODE_APPEND);
outputStream = new FileOutputStream (new File(patternDirectory.getAbsolutePath().toString()), true); // true will be same as Context.MODE_APPEND

5
谢谢你的回答。如果你没有发帖,我不确定我如何得出这个答案。否则我就不能将文件保存到位于内部文件目录(getFilesDir())的文件中。我很困惑为什么使用openFileOutput的被认为是Google文档中的方式不起作用。Google文档(http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int))让人非常困惑。 - raddevus

1
一个问题可能是你这样做: Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/com.example.pattern1/myfile.txt" 你创建了一个名为myfile.txt的目录。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接