0

我认为这一定不是一项很难实现的任务,我已经使用 HTC Desire 进行了管理,但由于某种原因,我无法在我的 android 应用程序中从三星 Galaxy S SD 卡中读取数据。

我用 :

public String writeFile1(String text) {

    File sdDir = Environment.getExternalStorageDirectory(); 

    File myFile = new File(sdDir+"/TextFiles/patientDetails.txt");
    try{
        myFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter = 
                                new OutputStreamWriter(fOut);
        myOutWriter.write(text);
        myOutWriter.close();
        fOut.close();
        return "success";
    }catch (IOException e){
        e.printStackTrace();
        return "fail";
    }
}

这很好用!文件内容被保存,我很高兴。但是,当我使用...进行反向操作时

//
               File f = new File(Environment.getExternalStorageDirectory()+fileName);

           FileInputStream 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
           String s = "";
           while((readString = buf.readLine())!= null){
               s+=readString;   
           }
           return s;

        } catch (FileNotFoundException e) {

           e.printStackTrace();

        } catch (IOException e){

           e.printStackTrace();
        }

我收到一个文件未找到异常!我刚刚写信给它,当我安装 SD 卡时可以看到我写的内容。

有人知道解决方案吗?谢谢

4

2 回答 2

0

您使用了错误的构造函数,您应该使用

File f = new File(Environment.getExternalStorageDirectory(), "filename");

代替

 File f = new File(Environment.getExternalStorageDirectory()+fileName);

现在你的代码可以正常工作了。

于 2011-10-10T11:03:44.620 回答
0

像这样初始化文件对象时会发生什么

Environment.getExternalStorageDirectory()+fileName

在这首先发生的事情中,您会以这种方式获得路径

/sdcard

并与文件名连接,然后以这种方式获得结果

filename = "test.txt";

path > /sdcardtext.txt

现在检查是否未找到此文件,因此请注意检查文件对象的完整路径。

接下来你可以像这样使用

File f = new File(Environment.getExternalStorageDirectory(), "filename");
于 2011-10-10T11:08:42.127 回答