Java IllegalArgumentException:文件包含路径分隔符 Android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27053487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IllegalArgumentException: File contains a path separator Android
提问by Talal Saleem
I'm trying to write to an output file on my HTC One and get the following message in the LogCat:
我正在尝试写入 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 contains a path separator
11-21 08:05:18.228:W/System.err(6609):java.lang.IllegalArgumentException:文件/storage/emulated/0/com.example.pattern1/myfile.txt 包含路径分隔符
The source code is given below:
源代码如下:
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();
}
I would appreciate if someone can help identify the problem.
如果有人可以帮助确定问题,我将不胜感激。
回答by Blue_Alien
The openFileInput method will not accept path separators.('/')
openFileInput 方法不接受路径分隔符。('/')
it accepts only the name of the file which you want to open/access. so change the statement
它只接受您要打开/访问的文件的名称。所以改变声明
outputStream = openFileOutput(patternDirectory.getAbsolutePath().toString(), Context.MODE_APPEND);
to
到
outputStream = new FileOutputStream (new File(patternDirectory.getAbsolutePath().toString()), true); // true will be same as Context.MODE_APPEND
回答by ?tefan Iulian
One problem may be the fact that you do:
Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/com.example.pattern1/myfile.txt"
You create a directory that has name myfile.txt
一个问题可能是您这样做的事实:
Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/com.example.pattern1/myfile.txt"
您创建了一个名为 myfile.txt 的目录