【问题标题】:Reading and writing to text files on Samsung Galaxy S sd card读取和写入三星 Galaxy S sd 卡上的文本文件
【发布时间】:2011-10-10 19:08:42
【问题描述】:

我认为这一定不是一个很难实现的任务,我已经使用 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 卡时可以看到我写的内容。

有人知道这个问题的解决方案吗?谢谢

【问题讨论】:

  • 只是为了确定,你的阅读方法可以Log.d(f.toString())吗?
  • 文件 myFile = new File(sdDir+"/TextFiles/patientDetails.txt");与您用于读取文件的路径相同吗 File f = new File(Environment.getExternalStorageDirectory()+fileName); ?确保它。所以,我觉得 fileName="/TextFiles/patientDetails.txt" 对吧?

标签: android sd-card galaxy


【解决方案1】:

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

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

而不是

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

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

【讨论】:

    【解决方案2】:

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

    Environment.getExternalStorageDirectory()+fileName
    

    在这种情况下,首先你会得到这样的路径

    /sdcard
    

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

    filename = "test.txt";
    
    path > /sdcardtext.txt
    

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

    接下来你可以像这样使用

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

    【讨论】:

    • 好的,我想我找到了解决方案——出于某种原因,我不得不使用 Environment.getExternalStorageDirectory().getAbsolutePath() 这确保它搜索了 mnt\sdcard\text.txt 文件夹三星 Galaxy S 喜欢存储文件,而不仅仅是 HTC Desire 存储文件的 sdcard\text.txt。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2014-03-07
    • 1970-01-01
    相关资源
    最近更新 更多