2012-04-23 43 views
1

我有这个功能,当我调用它时,它不会返回任何东西。试图读取SD卡上的文件到变量

public String getfileFromSDCard(String filename){//get the file 
    String text; 
    text = ""; 

    File root = new File(Environment.getExternalStorageDirectory(), "Notes"); 
    if (!root.exists()) { 
     root.mkdirs(); 
    } 
    File file = new File(root,"file.txt"); 
    try { 
     BufferedReader br = new BufferedReader(new FileReader(file)); 
     String str; 

     while ((str = br.readLine()) != null) { 
      text = text + str; 
     } 
     br.close(); 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } 
    Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); 
    return text; 
} 

我是否需要任何许可添加到我的Android manifiest以外

...使用许可权的android:NAME = “android.permission.WRITE_EXTERNAL_STORAGE” ......(我又写道这一行权在代码中)

我有这样一个已加入并运行,因为我可以很容易地编写一个文件,但我不能读它之后

这是我打电话是从的onCreate

功能
TextView countDisplay = new TextView(this); 
    CreatefiletoSDCard("testnumberone.txt","22222fkdf sdjf hjsdf sdj fsdf "); 
    countDisplay.setText(getfileFromSDCard("testnumberone.txt")); 

    this.setContentView(countDisplay); 

ps:CreatefiletoSDCard()的作品。

回答

1

尽管您在getfileFromSDCard()方法中传递了filename参数,但您似乎已将您正在读取的实际文件(名称)硬编码为file.txt。猜测你用来创建你的测试文件的文件名,这个错误可能是你试图从一个不存在的文件中读取,不管你真正传入该方法的名字是什么。

换句话说,你可能想更改以下行:

File file = new File(root,"file.txt"); 

到:

File file = new File(root,filename); 
+0

感谢,这是我的愚蠢的错误,我没看出来 – user1342645 2012-04-23 01:29:50