2011-02-24 81 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