开发者

Reading and writing to text files on Samsung Galaxy S sd card

开发者 https://www.devze.com 2023-04-12 11:49 出处:网络
I am thinking that this must not be a very difficult task to achieve and i have managed it with the HTC Desire but for some reason I cannot read from the Samsung Galaxy S SD card in my android applica

I am thinking that this must not be a very difficult task to achieve and i have managed it with the HTC Desire but for some reason I cannot read from the Samsung Galaxy S SD card in my android application.

I use :

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";
  开发者_如何学运维  }
}

and this works fine! The file content gets saved and i am very happy. However, when I do the reverse using...

//
               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();
        }

I receive a file not found exception! I just wrote to it and can see what I wrote when I mount the SD Card.

Does someone know the solution to this? Thanks


You are using wrong constructor you should use

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

instead of

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

Now your code will work fine.


What happen when you initializing your file object like this

Environment.getExternalStorageDirectory()+fileName

in this what happen first you getting the path like this way

/sdcard

and concatenate with the file name then you getting the result this way

filename = "test.txt";

path > /sdcardtext.txt

now check that this file didn't found so beware check the complete path for file object.

next thing you can use like this way

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号