IllegalArgumentException:文件包含路径分隔符Android

Tal*_*eem 4 java android exception file illegalargumentexception

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

11-21 08:05:18.228:W/System.err(6609):java.lang.IllegalArgumentException:File /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();
    }
Run Code Online (Sandbox Code Playgroud)

如果有人可以帮助确定问题,我将不胜感激.

Blu*_*ien 16

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

它只接受您要打开/访问的文件的名称.所以改变声明

outputStream = openFileOutput(patternDirectory.getAbsolutePath().toString(), Context.MODE_APPEND);
Run Code Online (Sandbox Code Playgroud)

outputStream = new FileOutputStream (new File(patternDirectory.getAbsolutePath().toString()), true); // true will be same as Context.MODE_APPEND
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的回答.如果你还没发布,我不确定如何得到这个答案.我无法保存到位于内部文件目录(getFilesDir())的文件中.我很困惑为什么谷歌所记录的使用openFileOutput的方法不起作用.非常混淆Google文档(http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String,int))). (3认同)