2012-09-13 135 views
0

下面幾行,我創建了「Environment.getExternalStorageDirectory()」文件如何將數據寫入到文件

File dir = Environment.getExternalStorageDirectory(); 
File file = new File(dir,"/DCIM/"+fileTitle); 

我的問題是:如何將文本數據寫入到該創建的文件?

+0

你想創建什麼樣的文件?文本?二進制? – marwinXXII

+0

我想創建一個文本文件 – LetsamrIt

回答

0

從這個tutorial,你可以去看看:

//Writing a file... 



try { 
     // catches IOException below 
     final String TESTSTRING = new String("Hello Android"); 

     /* We have to use the openFileOutput()-method 
     * the ActivityContext provides, to 
     * protect your file from others and 
     * This is done for security-reasons. 
     * We chose MODE_WORLD_READABLE, because 
     * we have nothing to hide in our file */    
     FileOutputStream fOut = openFileOutput("samplefile.txt", 
                  MODE_WORLD_READABLE); 
     OutputStreamWriter osw = new OutputStreamWriter(fOut); 

     // Write the string to the file 
     osw.write(TESTSTRING); 

     /* ensure that everything is 
     * really written out and close */ 
     osw.flush(); 
     osw.close(); 

//Reading the file back... 

     /* We have to use the openFileInput()-method 
     * the ActivityContext provides. 
     * Again for security reasons with 
     * openFileInput(...) */ 

     FileInputStream fIn = openFileInput("samplefile.txt"); 
     InputStreamReader isr = new InputStreamReader(fIn); 

     /* Prepare a char-Array that will 
     * hold the chars we read back in. */ 
     char[] inputBuffer = new char[TESTSTRING.length()]; 

     // Fill the Buffer with data from the file 
     isr.read(inputBuffer); 

     // Transform the chars to a String 
     String readString = new String(inputBuffer); 

     // Check if we read back the same chars that we had written out 
     boolean isTheSame = TESTSTRING.equals(readString); 

     Log.i("File Reading stuff", "success = " + isTheSame); 

    } catch (IOException ioe) 
     {ioe.printStackTrace();} 
+0

我試過了,但是當我檢查文件是否實際創建或沒有創建時,我發現沒有創建文件 – LetsamrIt

+0

您是否在應用程序清單中設置了權限? – Swayam

0

這裏有一個快速片斷數據到一個文件中寫道。請注意,它設計爲在單獨的線程中運行,因此您不會在主UI線程中執行文件IO操作。

new Thread(new Runnable() { 
    public void run() { 
    String FILENAME = "hello_file"; 
    String string = "hello world!"; 

    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
    fos.write(string.getBytes()); 
    fos.close(); 
    } 
}).start();