External Storage read write file

AndroidManifest.xml

   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

MyActivity.java

	/* Checks if external storage is available for read and write */
	public boolean isExternalStorageWritable() {
	    String state = Environment.getExternalStorageState();
	    if (Environment.MEDIA_MOUNTED.equals(state)) {
	        return true;
	    }
	    return false;
	}	
 
 
 
   private String readFileOnExternalSD(String fileName){
    	File sdcard = Environment.getExternalStorageDirectory();
 
    	//Get the text file
    	File file = new File(sdcard.getAbsolutePath() + "/myfolder",fileName);
 
    	//Read text from file
    	StringBuilder text = new StringBuilder();
 
    	try {
    	    BufferedReader br = new BufferedReader(new FileReader(file));
    	    String line;
 
    	    while ((line = br.readLine()) != null) {
    	        text.append(line);
    	        text.append('\n');
    	    }
    	    br.close();
    	}
    	catch (IOException e) {
    	    // error handling here
    	}
        return text.toString();
    }
 
 
   private void writeToSDcardFile(String fileName, String sSomeText) {
        File sdcard = android.os.Environment.getExternalStorageDirectory();
        File dir = new File(sdcard.getAbsolutePath() + "/myfolder");
        dir.mkdirs();
        File file = new File(dir, fileName);// for example "myData.txt"
        try {
            FileOutputStream f = new FileOutputStream(file);
            PrintWriter pw = new PrintWriter(f);
            pw.println(sSomeText +"Hello world!");
            pw.println("Other text");
            pw.flush();
            pw.close();
            f.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
This entry was posted in Android Examples Code and tagged . Bookmark the permalink.


Comments are closed.

2,446 views