2014-11-21 67 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目錄

相關問題