2011-02-24 104 views
0

在下面的代碼中,我想創建一個SD卡中的文件。但它沒有給出任何有效的輸出。僅顯示hello world ...在哪裏顯示「文件創建」消息以及文​​件的存儲位置?android未能顯示結果

package com.read; 

import java.io.FileOutputStream; 
import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 

public class read extends Activity { 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 


    String FILENAME = "hello_file"; 
    String string = "hello world!"; 
    try{ 
    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
    fos.write(string.getBytes()); 
    fos.close(); 
    }catch(Exception e){} 

    System.out.println("File created"); 

} 
} 

回答

0

使用此方法,您試圖在手機的內部存儲器中創建一個文件。

只需使用此代碼:

FileOuputStream fos = new FileOutputStream("/sdcard/" + FILENAME); 

它會在你的SD卡的根文件夾中創建一個文件。

+0

它的工作原理..謝謝 – vnshetty 2011-02-24 07:19:53

2

試試下面的代碼可以幫助你

try { 
File root = Environment.getExternalStorageDirectory(); 
if (root.canWrite()){ 
    File gpxfile = new File(root, "gpxfile.gpx"); 
    FileWriter gpxwriter = new FileWriter(gpxfile); 
    BufferedWriter out = new BufferedWriter(gpxwriter); 
    out.write("Hello world"); 
    out.close(); 
} 
}catch (IOException e) { 
    Log.e(TAG, "Could not write file " + e.getMessage()); 
} 

注:對於這個是工作的模擬器或設備必須具備SD卡

編輯:對於讀取文件fromSDCard

try{ 

File f = new File(Environment.getExternalStorageDirectory()+"/filename.txt"); 
    fileIS = new FileInputStream(f); 
    BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS)); 
    String readString = new String(); 
    //just reading each line and pass it on the debugger 
    while((readString = buf.readLine())!= null){ 
     Log.d("line: ", readString); 
    } 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e){ 
    e.printStackTrace(); 
} 
+0

它的工作太謝謝... – vnshetty 2011-02-24 07:25:08

+0

我該如何修改此代碼來讀取文件內容並將其顯示在模擬器中? TIA – vnshetty 2011-02-24 07:33:51

+0

我編輯了我的答案檢查 – ingsaurabh 2011-02-24 07:40:26