2014-11-21 71 views
3

我试图写一个输出文件在我的HTC One和在logcat中得到以下信息:抛出:IllegalArgumentException:文件包含路径分隔符的Android

8月11日至21日: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(); 
    } 

如果有人能帮助识别问题,我将不胜感激。

+1

【JAVA的可能重复.lang.IllegalArgumentException:包含路径分隔符](http://stackoverflow.com/questions/5963535/java-lang-illegalargumentexception-contains-a-path-separator) – timrau 2014-11-21 03:17:09

+0

@Talal Saleem哪条线给你错误? – 2014-11-21 03:19:43

+0

@timrau你的链接是输入案例,这是关于输出。轻微,我知道。 – 2016-10-26 19:33:32

回答

14

的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 
+2

感谢您的回答。我不知道如果你没有发布它,我会如何得到这个答案。否则我无法保存到位于内部文件目录(getFilesDir())中的文件中。我很困惑为什么所谓Google使用openFileOutput的方法无效。 Google文档非常混乱(http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String,int))。 – raddevus 2015-11-10 15:11:47

1

一个问题可能是你做的事实: Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/com.example.pattern1/myfile.txt" 您创建具有名称的myfile.txt目录

相关问题