2017-06-03 113 views
0

我已將此代碼用於在手機的外部存儲器中創建文件。請注意,我已經在我的Manifest文件中設置了讀寫的權限。我的LogCat顯示如下。我無法在該特定位置看到文件20170602.txt。在我的Download文件夾中,沒有任何具有該名稱的文件。誰能告訴我我哪裏出錯了。文件未在手機的外部存儲器中創建

D/tag: Directory: /storage/emulated/0/Android/data/com.pc.tab/files/Download 
D/tag: File: /storage/emulated/0/Android/data/com.pc.tab/files/Download/20170605.txt 

UPDATE

我使用MOTO G4運行這個程序。我在內部存儲上找到了20170602.txt文件。

File Manager --> `LOCAL` tab (Upper right) --> Internal Storage --> Android --> data --> com.pc.tab --> files --> Download --> 20170602.txt 
+0

有什麼原木e.printStackTrace()? –

+0

問題 - 您是否[請求/保護API> 22的權限](https://developer.android.com/training/permissions/requesting.html)? (可能不需要下載目錄..不確定)另外,你是否得到了捕獲的任何錯誤? – fattire

+0

printStackTrace沒有錯誤日誌。 @ A.Edwar – Chip

回答

1

它的目錄和文件本身

File directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); 
File file = new File(directory, fileName); 

在你的代碼調用你的文件mkdirs想寫分開是很重要的,它是因爲mkdirs的錯誤,使您的文件是一個目錄。您應該僅爲該目錄調用mkdirs,以便在其不存在的情況下創建它,並且在爲該文件創建新的FileOutputStream對象時將自動創建該文件。

您的代碼應該是這樣的:

SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); 
Date now = new Date(); 
String fileName = formatter.format(now) + ".txt"; //like 20170602.txt 

File directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); 
File file = new File(directory, fileName); 

String bodyOfFile = "Body of file!"; 
FileOutputStream fos = null; 
try { 
    fos = new FileOutputStream(file); 
    fos.write(bodyOfFile.getBytes()); 
    fos.close(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
+0

明白了。請看我更新的問題。 我以前每次都會看到'ExternalStorage',因爲getExternalFilesDir是SD卡的內部存儲器。但是在我的手機中,它是在我更新的問題中提到的內部存儲中創建的。它有多遠?還是我假設內部存儲錯誤? – Chip

相關問題