IllegalArgumentException: File contains Android path separator
I am trying to write to an output file on my HTC One and get the following message in the LogCat:
11-21 08: 05: 18.228: W / System.err (6609): java.lang.IllegalArgumentException: File / storage / emulated / 0 / com.example.pattern1 / myfile.txt contains path separator
The source code is shown 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 be grateful if someone can help identify the problem.
+3
source to share
2 answers
The openFileInput method will not accept path separators. ('/')
it only accepts the name of the file you want to open / retrieve. 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
+14
source to share