2014-03-03 50 views
0

我想創建一個包含字符串的文本文件。Android文件不創建

String string = "hello!"; 

File file = new File(Environment.getExternalStorageDirectory(),"test.txt"); 

FileOutputStream fos = new FileOutputStream(file); 
fos.write(string.getBytes()); 
fos.close(); 

我有適當的權限。

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.latorre" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="10" /> 

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />... 

但是文件沒有被創建。爲什麼?

+1

BTW:targetting API 10?真? – donfuxx

+0

任何日誌? – njzk2

+0

在寫入之前,應檢查外部存儲器的狀態。 [這裏](https://developer.android.com/training/basics/data-storage/files.html#WriteExternalStorage)是一個很好的介紹。 –

回答

1
public void writefile(String word1) 
     try { 
        String path = sdCard.getAbsolutePath() + "/"; 

     File logFile = new File(path + "test.txt"); 
     if (!logFile.exists()) { 
      logFile.createNewFile(); 
     } 

     // BufferedWriter for performance, true to set append to file 

     FileWriter fw = new FileWriter(logFile, true); 
     BufferedWriter buf = new BufferedWriter(fw); 


      buf.append(word1); 
      buf.newLine(); 
      buf.flush(); 

     } 
     buf.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
+0

它的工作原理非常完美。謝謝!! – user3361635

0
String string = "hello!"; 

File file = new File(Environment.getExternalStorageDirectory() + "/", "test.txt"); 
if (!file.exists()){ 
    file.createNewFile(); 
} 

FileOutputStream fos = new FileOutputStream(file, true); 
fos.write(string.getBytes()); 
fos.close(); 
+0

您能否提供一些關於該代碼的上下文/解釋?雖然這可能解決問題,但OP詢問*爲什麼*該文件未被創建。請解釋什麼是問題,以及您的代碼如何解決它。 –

+0

雖然我不確定,但我認爲當您使用構造函數File(path,name)創建文件時,該文件實際上並不是在存儲上創建的,而是在內存中創建的。 createNewFile()方法實際上是在存儲上創建文件。 – SilverZ