Android Tutorial - Core Class : Environment
Create a new directory on external storage
package app.test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.widget.TextView; import android.widget.Toast; public class Test extends Activity { private static final String FILENAME = "data.txt"; private static final String DNAME = "myfiles"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); setContentView(tv); File rootPath = new File(Environment.getExternalStorageDirectory(), DNAME); if(!rootPath.exists()) { rootPath.mkdirs(); } File dataFile = new File(rootPath, FILENAME); if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Toast.makeText(this, "Cannot use storage.", Toast.LENGTH_SHORT).show(); finish(); return; } try { FileOutputStream mOutput = new FileOutputStream(dataFile, false); String data = "DATA"; mOutput.write(data.getBytes()); mOutput.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream mInput = new FileInputStream(dataFile); byte[] data = new byte[128]; mInput.read(data); mInput.close(); String display = new String(data); tv.setText(display.trim()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } dataFile.delete(); }
}
May crash when External-Media is not mounted.
// Created by plusminus on 13:24:05 - 21.09.2008 //package org.andnav2.osm.util; import java.util.Comparator; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; class Util { public static final String DEBUGTAG = "OPENSTREETMAP"; public static final String BASEPATH_ON_EXTERNAL_MEDIA = "andnav2/"; public static final String SDCARD_SAVEDROUTES_PATH = "routes/"; public static final String SDCARD_SAVEDTRACES_PATH = "traces/"; public static final String SDCARD_SKYHOOKCACHE_PATH = "skyhookcache/"; public static final String SDCARD_TILE_PATH = "tiles/"; public static final int NOT_SET = Integer.MIN_VALUE; public static final int Y = 0; public static final int X = 1; /** * May crash when External-Media is not mounted. * @return path, like <code>"/sdcard/andnav2/"</code> always ending with a <code>"/"</code> */ public static final String getAndNavExternalStoragePath(){ final String absoluteExternalPath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath(); if(absoluteExternalPath.endsWith("/")) { return absoluteExternalPath + BASEPATH_ON_EXTERNAL_MEDIA; } else { return absoluteExternalPath + "/" + BASEPATH_ON_EXTERNAL_MEDIA; } } }
is Storage Readable/Writable
//package ch.uzh.ifi.attempto.mobileape; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.os.Environment; import android.widget.Toast; public class Utils { public static boolean isStorageWritable() { boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; } //Toast.makeText(TransAnd.this, "SD: available: " + mExternalStorageAvailable + "; writable: " + mExternalStorageWriteable, Toast.LENGTH_LONG).show(); return (mExternalStorageAvailable && mExternalStorageWriteable); } public static boolean isStorageReadable() { boolean mExternalStorageAvailable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { mExternalStorageAvailable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { mExternalStorageAvailable = true; } return mExternalStorageAvailable; } /** * * @param filePath * @return * @throws java.io.IOException */ public static String readFileAsString(String filePath) throws java.io.IOException { byte[] buffer = new byte[(int) new File(filePath).length()]; BufferedInputStream f = null; try { f = new BufferedInputStream(new FileInputStream(filePath)); f.read(buffer); } finally { if (f != null) try { f.close(); } catch (IOException ignored) { } } return new String(buffer); } public static List<String> readFileToLines(String filePath) throws IOException { List<String> lines = new ArrayList<String>(); FileInputStream fstream = new FileInputStream(filePath); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { lines.add(strLine); } in.close(); return lines; } public static void showMessage(Context context, String message) { Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } public static void showException(Context context, Exception e) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show(); }
}
Get External Storage Directory
public static File GetSDDir() { return Environment.getExternalStorageDirectory();
}
Environment.MEDIA_MOUNTED, Environment.MEDIA_MOUNTED_READ_ONLY
//package com.loveofsoftware.fotolab; import java.io.File; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Environment; class Util { public static String getNewName(String originalName, Context ctx) { if(null == originalName) { originalName = "tmp"; System.out.println("ERROR: Why did i get null orginalName?"); } int MAX_ATTEMPTS = 10; int attempts = 0; String result = getFotolabDir(ctx);// + Constants.APP_NAME + "/"; while(attempts++ < MAX_ATTEMPTS) { String picName = originalName.substring(originalName.lastIndexOf("/")+1); //remove the extension such as .jpg, .png etc picName = picName.replaceAll("\\..*", ""); picName = result + picName + System.currentTimeMillis() + ".png"; File file = new File(picName); if(!file.exists()) return picName; } throw new RuntimeException("couldn't get a name"); } private static void alert(String msg, Context ctx) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setMessage(msg) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }) ; AlertDialog alert = builder.create(); alert.show(); } public static String getFotolabDir(Context ctx) { boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; } if(!mExternalStorageAvailable) { alert("External media is not available. App may not function correctly",ctx); }else if(!mExternalStorageWriteable) { alert("External media is not writable. App may not function correctly",ctx); } return Environment.getExternalStorageDirectory().getAbsolutePath()+"/fotolab/"; }
}
Utility class used to deal with SD card cache.
package net.javalib.flickr.search.util; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; /** * Utility class used to deal with SD card cache. */ public class CacheUtil { /** Cache root */ private static File root; private CacheUtil() {} static { root = Environment.getExternalStorageDirectory(); root = new File(root,"FlickrSearch/cache"); } public static File file(String cacheKey) { return new File(root,cacheKey); } public static void deleteCache() { deleteDir(root); } public static void deleteDir(File dir) { if (!dir.isDirectory()) return; File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) deleteDir(file); else { file.delete(); } } } public static boolean exists(String cacheKey) { return file(cacheKey).exists(); } public static Bitmap getBitmap(String cacheKey) { if (!exists(cacheKey)) return null; File file = file(cacheKey); InputStream in = null; try { in = new FileInputStream(file); return BitmapFactory.decodeStream(in); } catch (Exception e) { return null; } finally { if (in != null) try { in.close(); } catch (Exception e) {} } }
}
return True if the external storage is available/writable.
package be.ac.ulb.lisa.idot.android.commons; import android.os.Environment; /** * The class Geometry contains external storage functions. * * @author Pierre Malarme * @version 1.O * */ public class ExternalStorage { // --------------------------------------------------------------- // + <static> FUNCTIONS // --------------------------------------------------------------- /** * @return True if the external storage is available. * False otherwise. */ public static boolean checkAvailable() { // Retrieving the external storage state String state = Environment.getExternalStorageState(); // Check if available if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; } /** * @return True if the external storage is writable. * False otherwise. */ public static boolean checkWritable() { // Retrieving the external storage state String state = Environment.getExternalStorageState(); // Check if writable if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; }
}