我试图写入我的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();
}
如果有人能帮助您找出问题,我将不胜感激。
答案 0 :(得分:15)
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
答案 1 :(得分:1)
您可能遇到的一个问题是:
Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/com.example.pattern1/myfile.txt"
您创建名为myfile.txt