2011年7月27日 星期三

[Android] Read string from external files

There is a txt file named text.txt and it's content as below.
hello string.

I put the file into sdcard of my Pad under folder named /myfile.
I want get the content of the file in my android program.

At first of all, making sure your sdcard is ready.

       File fileSDCard = null;
       if(Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED))
       {
          return;
       }
       else
       {
           fileSDCard = Environment.getExternalStorageDirectory();
       }

next, open the file and read it.
       FileInputStream fstream = null;
       String readString = "";  
       try 
       {
           fstream = new FileInputStream(fileSDCard.getParent() + "/" + fileSDCard.getName() + "/myfile/test.txt");
           StringBuffer buffer = new StringBuffer();
           int readChar; 
           while ((readChar = fstream.read()) != -1) 
           { 
               buffer.append((char) readChar); 
           } 
           fstream.close(); 
           readString = buffer.toString(); 
       } 
       catch (Exception e) 
       {
           e.printStackTrace();
       }

It's done, so easy, isn't it?