Android Tutorial - File : Comprehensive file handling
Read the created file and display to the screen
package app.test; 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.widget.TextView; public class Test extends Activity { private static final String FILENAME = "data.txt"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); setContentView(tv); try { FileOutputStream mOutput = openFileOutput(FILENAME, Activity.MODE_PRIVATE); String data = "THIS DATA WRITTEN TO A FILE"; mOutput.write(data.getBytes()); mOutput.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream mInput = openFileInput(FILENAME); 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(); } deleteFile(FILENAME); } }
Create a Uri for files on external storage
package app.test; import java.io.File; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Create a Uri for files on external storage File externalFile = new File(Environment.getExternalStorageDirectory(), "a.pdf"); Uri external = Uri.fromFile(externalFile); viewPdf(external); shareContent("Check this out!"); } private void shareContent(String update) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, update); startActivity(Intent.createChooser(intent, "Share...")); } private void viewPdf(Uri file) { Intent intent; intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(file, "application/pdf"); try { startActivity(intent); } catch (ActivityNotFoundException e) { // No application to view, ask to download one AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("No Application Found"); builder.setMessage("Download one from Android Market?"); builder.setPositiveButton("Yes, Please", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent marketIntent = new Intent(Intent.ACTION_VIEW); marketIntent .setData(Uri .parse("market://details?id=com.adobe.reader")); startActivity(marketIntent); } }); builder.setNegativeButton("No, Thanks", null); builder.create().show(); } } }
Create a Uri for files on internal storage
package app.test; import java.io.File; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); File internalFile = getFileStreamPath("a.pdf"); Uri internal = Uri.fromFile(internalFile); viewPdf(internal); shareContent("Check this out!"); } private void shareContent(String update) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, update); startActivity(Intent.createChooser(intent, "Share...")); } private void viewPdf(Uri file) { Intent intent; intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(file, "application/pdf"); try { startActivity(intent); } catch (ActivityNotFoundException e) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("No Application Found"); builder.setMessage("Download one from Android Market?"); builder.setPositiveButton("Yes, Please", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent marketIntent = new Intent(Intent.ACTION_VIEW); marketIntent.setData(Uri.parse("market://details?id=com.adobe.reader")); startActivity(marketIntent); } }); builder.setNegativeButton("No, Thanks", null); builder.create().show(); } } }
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; public class Test extends Activity { private final static String NOTES="notes.txt"; private EditText editor; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); editor=(EditText)findViewById(R.id.editor); Button btn=(Button)findViewById(R.id.close); btn.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { finish(); } }); } public void onResume() { super.onResume(); try { InputStream in=openFileInput(NOTES); if (in!=null) { InputStreamReader tmp=new InputStreamReader(in); BufferedReader reader=new BufferedReader(tmp); String str; StringBuilder buf=new StringBuilder(); while ((str = reader.readLine()) != null) { buf.append(str+"\n"); } in.close(); editor.setText(buf.toString()); } } catch (java.io.FileNotFoundException e) { // that's OK, we probably haven't created it yet } catch (Throwable t) { Toast .makeText(this, "Exception: "+t.toString(), 2000) .show(); } } public void onPause() { super.onPause(); try { OutputStreamWriter out= new OutputStreamWriter(openFileOutput(NOTES, 0)); out.write(editor.getText().toString()); out.close(); } catch (Throwable t) { Toast .makeText(this, "Exception: "+t.toString(), 2000) .show(); } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <Button android:id="@+id/close" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Close" /> <EditText android:id="@+id/editor" android:layout_width="fill_parent" android:layout_height="fill_parent" android:singleLine="false" android:gravity="top" /> </LinearLayout>
View/Listen to media file
package app.test; import java.io.File; import android.app.ListActivity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class Test extends ListActivity { Cursor cursor; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String[] columns = { android.provider.MediaStore.Audio.Albums._ID, android.provider.MediaStore.Audio.Albums.ALBUM }; cursor = managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, columns, null, null, null); String[] displayFields = new String[] { MediaStore.Audio.Albums.ALBUM }; int[] displayViews = new int[] { android.R.id.text1 }; setListAdapter(new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, displayFields, displayViews)); } protected void onListItemClick(ListView l, View v, int position, long id) { if (cursor.moveToPosition(position)) { int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA); int mimeTypeColumn = cursor.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE); String audioFilePath = cursor.getString(fileColumn); String mimeType = cursor.getString(mimeTypeColumn); Intent intent = new Intent(android.content.Intent.ACTION_VIEW); File newFile = new File(audioFilePath); intent.setDataAndType(Uri.fromFile(newFile), mimeType); startActivity(intent); } } }
File Copy Util
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Serializable; import java.io.Writer; public class IOUtils{ private IOUtils(){} private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; public static String toString(InputStream input) throws IOException { StringBuilderWriter sw = new StringBuilderWriter(); copy(input, sw); return sw.toString(); } /** * Copy bytes from an <code>InputStream</code> to chars on a * <code>Writer</code> using the default character encoding of the platform. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedInputStream</code>. * <p> * This method uses {@link InputStreamReader}. * * @param input the <code>InputStream</code> to read from * @param output the <code>Writer</code> to write to * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since Commons IO 1.1 */ public static void copy(InputStream input, Writer output) throws IOException { InputStreamReader in = new InputStreamReader(input); copy(in, output); } /** * Copy bytes from an <code>InputStream</code> to chars on a * <code>Writer</code> using the specified character encoding. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedInputStream</code>. * <p> * Character encoding names can be found at * <a href="http://www.iana.org/assignments/character-sets">IANA</a>. * <p> * This method uses {@link InputStreamReader}. * * @param input the <code>InputStream</code> to read from * @param output the <code>Writer</code> to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since Commons IO 1.1 */ public static void copy(InputStream input, Writer output, String encoding) throws IOException { if (encoding == null) { copy(input, output); } else { InputStreamReader in = new InputStreamReader(input, encoding); copy(in, output); } } // copy from Reader //----------------------------------------------------------------------- /** * Copy chars from a <code>Reader</code> to a <code>Writer</code>. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedReader</code>. * <p> * Large streams (over 2GB) will return a chars copied value of * <code>-1</code> after the copy has completed since the correct * number of chars cannot be returned as an int. For large streams * use the <code>copyLarge(Reader, Writer)</code> method. * * @param input the <code>Reader</code> to read from * @param output the <code>Writer</code> to write to * @return the number of characters copied * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @throws ArithmeticException if the character count is too large * @since Commons IO 1.1 */ public static int copy(Reader input, Writer output) throws IOException { long count = copyLarge(input, output); if (count > Integer.MAX_VALUE) { return -1; } return (int) count; } /** * Copy chars from a large (over 2GB) <code>Reader</code> to a <code>Writer</code>. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedReader</code>. * * @param input the <code>Reader</code> to read from * @param output the <code>Writer</code> to write to * @return the number of characters copied * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since Commons IO 1.3 */ public static long copyLarge(Reader input, Writer output) throws IOException { char[] buffer = new char[DEFAULT_BUFFER_SIZE]; long count = 0; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } /** * Copy chars from a <code>Reader</code> to bytes on an * <code>OutputStream</code> using the default character encoding of the * platform, and calling flush. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedReader</code>. * <p> * Due to the implementation of OutputStreamWriter, this method performs a * flush. * <p> * This method uses {@link OutputStreamWriter}. * * @param input the <code>Reader</code> to read from * @param output the <code>OutputStream</code> to write to * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since Commons IO 1.1 */ public static void copy(Reader input, OutputStream output) throws IOException { OutputStreamWriter out = new OutputStreamWriter(output); copy(input, out); // XXX Unless anyone is planning on rewriting OutputStreamWriter, we // have to flush here. out.flush(); } /** * Copy chars from a <code>Reader</code> to bytes on an * <code>OutputStream</code> using the specified character encoding, and * calling flush. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedReader</code>. * <p> * Character encoding names can be found at * <a href="http://www.iana.org/assignments/character-sets">IANA</a>. * <p> * Due to the implementation of OutputStreamWriter, this method performs a * flush. * <p> * This method uses {@link OutputStreamWriter}. * * @param input the <code>Reader</code> to read from * @param output the <code>OutputStream</code> to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since Commons IO 1.1 */ public static void copy(Reader input, OutputStream output, String encoding) throws IOException { if (encoding == null) { copy(input, output); } else { OutputStreamWriter out = new OutputStreamWriter(output, encoding); copy(input, out); // XXX Unless anyone is planning on rewriting OutputStreamWriter, // we have to flush here. out.flush(); } } } /** * {@link Writer} implementation that outputs to a {@link StringBuilder}. * <p> * <strong>NOTE:</strong> This implementation, as an alternative to * <code>java.io.StringWriter</code>, provides an <i>un-synchronized</i> * (i.e. for use in a single thread) implementation for better performance. * For safe usage with multiple {@link Thread}s then * <code>java.io.StringWriter</code> should be used. * * ***Copied & Pasted from apache commons-io because I dont want to add too many 3rd parties library to the app to keep it as small as possible*** * * @version $Revision$ $Date$ * @since IO 2.0 */ class StringBuilderWriter extends Writer implements Serializable { /** * */ private static final long serialVersionUID = 1L; private final StringBuilder builder; /** * Construct a new {@link StringBuilder} instance with default capacity. */ public StringBuilderWriter() { this.builder = new StringBuilder(); } /** * Construct a new {@link StringBuilder} instance with the specified capacity. * * @param capacity The initial capacity of the underlying {@link StringBuilder} */ public StringBuilderWriter(int capacity) { this.builder = new StringBuilder(capacity); } /** * Construct a new instance with the specified {@link StringBuilder}. * * @param builder The String builder */ public StringBuilderWriter(StringBuilder builder) { this.builder = (builder != null ? builder : new StringBuilder()); } /** * Append a single character to this Writer. * * @param value The character to append * @return This writer instance */ @Override public Writer append(char value) { builder.append(value); return this; } /** * Append a character sequence to this Writer. * * @param value The character to append * @return This writer instance */ @Override public Writer append(CharSequence value) { builder.append(value); return this; } /** * Append a portion of a character sequence to the {@link StringBuilder}. * * @param value The character to append * @param start The index of the first character * @param end The index of the last character + 1 * @return This writer instance */ @Override public Writer append(CharSequence value, int start, int end) { builder.append(value, start, end); return this; } /** * Closing this writer has no effect. */ @Override public void close() { } /** * Flushing this writer has no effect. */ @Override public void flush() { } /** * Write a String to the {@link StringBuilder}. * * @param value The value to write */ @Override public void write(String value) { if (value != null) { builder.append(value); } } /** * Write a portion of a character array to the {@link StringBuilder}. * * @param value The value to write * @param offset The index of the first character * @param length The number of characters to write */ @Override public void write(char[] value, int offset, int length) { if (value != null) { builder.append(value, offset, length); } } /** * Return the underlying builder. * * @return The underlying builder */ public StringBuilder getBuilder() { return builder; } /** * Returns {@link StringBuilder#toString()}. * * @return The contents of the String builder. */ @Override public String toString() { return builder.toString(); } }
Copy File Thread
//package eecs.umich.threegtest; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import android.os.Environment; import android.util.Log; public class CopyFile extends Thread { String mSrc; String mDet; CopyFile(String Filename1) { mSrc = Filename1; mDet = "UMLogger.txt"; } public void run() { try { File root = Environment.getExternalStorageDirectory(); if (root.canWrite()) { File logfile = new File(root, mDet); FileOutputStream out = new FileOutputStream(logfile); FileInputStream fin = new FileInputStream(mSrc); byte[] buf = new byte[1024]; int len; while ((len = fin.read(buf)) > 0) { out.write(buf, 0, len); Log.v("check", "length is " + len); } fin.close(); out.close(); } } catch (IOException e) { Log.e("check", "Could not write file " + e.getMessage()); } } }
Adaptation of the class File to add some usefull functions
//package com.ovhoo.android.file; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import android.net.Uri; /** * Adaptation of the class File to add some usefull functions * @author mzalim * */ public class FileInterface{ public static enum fileSizeUnit {FILE_SIZE_BITS, FILE_SIZE_BYTES, FILE_SIZE_KIB, FILE_SIZE_MIB, FILE_SIZE_GIB, FILE_SIZE_TIB}; private File file; public FileInterface(File file) { this.file = file; } public FileInterface(String path) { this.file = new File(path); } public String getParentDir(){ String _parent = this.file.getParent(); if (_parent == null){ return "/"; }else{ return _parent; } } public ArrayList<FileInterface> ls(){ if (this.file.isDirectory()){ ArrayList<FileInterface> _retour = new ArrayList<FileInterface>(); java.io.File _files[] = this.file.listFiles(); for(int _index=0; _index < _files.length; _index ++){ _retour.add(new FileInterface(_files[_index])); } return _retour; } else{ return null; } } public ArrayList<FileInterface> ls(FilenameFilter filter){ if (this.file.isDirectory()){ ArrayList<FileInterface> _retour = new ArrayList<FileInterface>(); java.io.File _files[] = this.file.listFiles(filter); for(int _index=0; _index < _files.length; _index ++){ _retour.add(new FileInterface(_files[_index])); } return _retour; } else{ return null; } } /** * Returns the file size in human readable units * Defaut unit is in Bytes * @return file size as String */ public String getFileSize(fileSizeUnit unit){ long _size = this.file.length(); if (unit == null){ return _size + " Bytes"; } switch(unit){ case FILE_SIZE_BITS : return _size*8 + " Bits"; case FILE_SIZE_KIB : return _size/1024 + " KIB"; case FILE_SIZE_MIB : return _size/1048576 + " MIB"; case FILE_SIZE_GIB : return _size/1073741824 + " GIB"; default: return _size + " Bytes"; } } /** * Returns the file size in human readable units * calculate the best unit to use */ public String getFileSize(){ long _size = this.file.length(); if (_size>2073741824){ return _size/1073741824 + " GIB"; } else if (_size>10485760){ return _size/1048576 + " MIB"; } else if (_size>10240){ return _size/1024 + " KIB"; } else if (_size>10){ return _size + " Bytes"; } else{ return _size*8 + " Bits"; } } public String getName(){ return this.file.getName(); } public boolean isDirectory(){ return this.file.isDirectory(); } public String getPath(){ return this.file.getPath(); } public String getAbsolutePath(){ return this.file.getAbsolutePath(); } public boolean mkdirs(){ return this.file.mkdirs(); } public boolean renameTo(String name) { File _file= new File(this.getParentDir() + "/" + name); return this.file.renameTo(_file); } public boolean delete() { return this.file.delete(); } public Uri getUri() { return Uri.parse("file://"+ this.file.getAbsolutePath()); } public boolean equals(Object obj){ if (obj instanceof FileInterface){ return this.file.equals(((FileInterface)obj).file); } else{ return false; } } public File getFile() { return this.file; } }
Save to Android local file system
//package com.a4studio.android.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import android.os.Environment; import android.util.Log; public class NewsPersistence { private final static String TAG = NewsPersistence.class.getSimpleName(); private File sdcardStorage; private String sdcardPath; private String newsPath; private final static String PACKAGE_NAME = "news_wmu"; private final static String fileExtensionName = ".wdata"; private int fileNum = 0; public NewsPersistence() throws Exception { if(Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_REMOVED)) { throw new Exception("no external storage like sdcard"); } sdcardStorage = Environment.getExternalStorageDirectory(); sdcardPath = sdcardStorage.getParent() + java.io.File.separator + sdcardStorage.getName(); newsPath = sdcardPath+java.io.File.separator + PACKAGE_NAME; File newsFile = new File(newsPath); if(!newsFile.exists()) { newsFile.mkdir(); } } public synchronized List<String> getFileList() { List<String> files = new ArrayList<String>(); File dir = new File(newsPath); for(File file : dir.listFiles()) { if(file.isFile() && file.getName().endsWith(fileExtensionName)){ files.add(file.getName()); } } return files; } public synchronized void storeNewsItemList(List<NewsItem> items) throws IOException { for(NewsItem item : items) { fileNum++; long ticket = System.currentTimeMillis(); String filename = newsPath+java.io.File.separator + ticket+fileNum+fileExtensionName; File newfile = new File(filename); newfile.createNewFile(); ObjectOutputStream objOutput = new ObjectOutputStream(new FileOutputStream(newfile)); objOutput.writeObject(item); } } public synchronized void storeNewsItem(NewsItem item) throws IOException { Log.d(TAG, "storeNewsItem"+item.getContent()); fileNum++; long ticket = System.currentTimeMillis(); String filename = newsPath + java.io.File.separator + ticket + fileNum + fileExtensionName; File newfile = new File(filename); newfile.createNewFile(); ObjectOutputStream objOutput = new ObjectOutputStream( new FileOutputStream(newfile)); objOutput.writeObject(item); } public synchronized List<NewsItem> retrieveNewsItem() throws Exception { File dir = new File(newsPath); List<NewsItem> items = new ArrayList<NewsItem>(); for(File file : dir.listFiles()) { if(file.isFile() && file.getName().endsWith(fileExtensionName)) { ObjectInputStream input = new ObjectInputStream(new FileInputStream(file)); NewsItem item = (NewsItem)input.readObject(); Log.d(TAG, "retrieveNewsItem"+file.getName()); items.add(item); } } return items; } public synchronized void removeAllNewsItems() { File dir = new File(newsPath); for(File file : dir.listFiles()) { if(!file.delete()) { Log.e(TAG, "delete file "+file.getName() + "delete fail"); } } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } } class NewsItem implements Serializable{ /** * */ private static final long serialVersionUID = 1L; public final static String RESULT = "Result"; public final static String TITLE = "Title"; public final static String SUMMARY = "Summary"; public final static String URL = "Url"; public final static String CLICKURL = "ClickUrl"; public final static String NEWSSOURCE = "NewsSource"; public final static String NEWSSOURCEURL = "NewsSourceUrl"; public final static String LANGUAGE = "Language"; public final static String PUBLISHDATE = "PublishDate"; public final static String MODIFICATIONDATE = "ModificationDate"; private String title; private String summary; private String url; private String clickUrl; private String newsSource; private String newsSrouceUrl; private String language; private long publishDate; private long modifDate; private String content; /** * @return the title */ public String getTitle() { return title; } /** * @param title * the title to set */ public void setTitle(String title) { this.title = title; } /** * @return the summary */ public String getSummary() { return summary; } /** * @param summary * the summary to set */ public void setSummary(String summary) { this.summary = summary; } /** * @return the url */ public String getUrl() { return url; } /** * @param url * the url to set */ public void setUrl(String url) { this.url = url; } /** * @return the clickUrl */ public String getClickUrl() { return clickUrl; } /** * @param clickUrl * the clickUrl to set */ public void setClickUrl(String clickUrl) { this.clickUrl = clickUrl; } /** * @return the newsSource */ public String getNewsSource() { return newsSource; } /** * @param newsSource * the newsSource to set */ public void setNewsSource(String newsSource) { this.newsSource = newsSource; } /** * @return the newsSrouceUrl */ public String getNewsSrouceUrl() { return newsSrouceUrl; } /** * @param newsSrouceUrl * the newsSrouceUrl to set */ public void setNewsSrouceUrl(String newsSrouceUrl) { this.newsSrouceUrl = newsSrouceUrl; } /** * @return the language */ public String getLanguage() { return language; } /** * @param language * the language to set */ public void setLanguage(String language) { this.language = language; } /** * @return the publishDate */ public long getPublishDate() { return publishDate; } /** * @param publishDate * the publishDate to set */ public void setPublishDate(long publishDate) { this.publishDate = publishDate; } /** * @return the modifDate */ public long getModifDate() { return modifDate; } /** * @param modifDate * the modifDate to set */ public void setModifDate(long modifDate) { this.modifDate = modifDate; } /** * @return the content */ public String getContent() { return content; } /** * @param content the content to set */ public void setContent(String content) { this.content = content; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { // TODO Auto-generated method stub return this.title+"\n"+ this.summary +"\n"+ this.url+"\n"+ this.clickUrl+"\n"+ this.newsSource+"\n"+ this.newsSrouceUrl+"\n"+ this.language+"\n"+ this.publishDate+"\n"+ this.modifDate+"\n"; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
Using Ini file to manage Preferences
//package com.a4studio.android.newsreader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Properties; import android.content.Context; import android.util.Log; public class Preferences { private final static String TAG=Preferences.class.getSimpleName(); private Context context; public final static String PREF_FILE_NAME="prefs.ini"; public final static String TIME_KEY="time"; public final static String KEYWORD_KEY="keyword"; public final static String RESULT_NUM_KEY="result"; private Properties props; public Preferences( Context context) { this.context = context; boolean isExist =true; try { context.openFileInput(PREF_FILE_NAME); } catch (FileNotFoundException e) { Log.e(TAG, "can't read pref file", e); isExist = false; } props = new Properties(); if(!isExist) { reconstruct(); } props.clear(); FileInputStream fin; try { fin = context.openFileInput(PREF_FILE_NAME); props.load(fin); fin.close(); } catch (FileNotFoundException e) { Log.e(TAG, "can't read pref file", e); } catch (IOException e) { Log.e(TAG, "can't read pref file", e); } } public int getResultNumSetting() { String time = props.getProperty(RESULT_NUM_KEY, "1"); int timeValue; try { timeValue = Integer.parseInt(time); } catch(Exception e) { //the file could be crashed, so reconstruct one more reconstruct(); time = props.getProperty(RESULT_NUM_KEY, "1"); timeValue = Integer.parseInt(time); } return timeValue; } public long getTimeSetting() { String time = props.getProperty(TIME_KEY, "0"); long timeValue; try { timeValue = Long.parseLong(time); } catch(Exception e) { reconstruct(); time = props.getProperty(TIME_KEY, "0"); timeValue = Long.parseLong(time); } return timeValue; } public String getKeywordSetting() { return props.getProperty(KEYWORD_KEY, "science"); } public void setTimeSetting(long time) { try { Log.d(TAG, "setTimeSetting"); FileOutputStream fos = context.openFileOutput(PREF_FILE_NAME, Context.MODE_WORLD_WRITEABLE); props.setProperty(TIME_KEY, time+""); props.store(fos, "a4studio"); fos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Log.e(TAG, "can't read pref file", e); } catch (IOException e) { // TODO Auto-generated catch block Log.e(TAG, "can't read pref file", e); } } public void setKeywordSetting(String keyword) { try { Log.d(TAG, "setKeywordSetting"); FileOutputStream fos = context.openFileOutput(PREF_FILE_NAME, Context.MODE_WORLD_WRITEABLE); props.setProperty(KEYWORD_KEY, keyword); props.store(fos, "a4studio"); fos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Log.e(TAG, "can't read pref file", e); } catch (IOException e) { // TODO Auto-generated catch block Log.e(TAG, "can't read pref file", e); } } public void setResultNumSetting(int result) { try { Log.d(TAG, "setResultNumSetting"); FileOutputStream fos = context.openFileOutput(PREF_FILE_NAME, Context.MODE_WORLD_WRITEABLE); props.setProperty(RESULT_NUM_KEY, result+""); props.store(fos, "a4studio"); fos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Log.e(TAG, "can't read pref file", e); } catch (IOException e) { // TODO Auto-generated catch block Log.e(TAG, "can't read pref file", e); } } private void reconstruct() { try { Log.d(TAG, "reconstruct"); FileOutputStream fos = null; fos = context.openFileOutput(PREF_FILE_NAME, Context.MODE_WORLD_WRITEABLE); /* props.setProperty(TIME_KEY, System.currentTimeMillis()+""); props.setProperty(KEYWORD_KEY, "science"); props.store(fos, "reconstrut version");*/ fos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Log.e(TAG, "can't create pref file", e); } catch (IOException e) { // TODO Auto-generated catch block Log.e(TAG, "can't create pref file", e); } } }
File Cache
//package com.mediaportal.ampdroid.lists; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.content.Context; import android.graphics.Bitmap; public class FileCache { private File cacheDir; public FileCache(Context context){ //Find the dir to save cached images if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "aMPdroid/.Cache"); else cacheDir=context.getCacheDir(); if(!cacheDir.exists()) cacheDir.mkdirs(); } public File getFile(String filename){ //I identify images by hashcode. Not a perfect solution, good for the demo. //String filename=String.valueOf(url.hashCode()); File f = new File(cacheDir, filename); return f; } public void clear(){ File[] files=cacheDir.listFiles(); for(File f:files) f.delete(); } public void storeBitmap(Bitmap _bitmap, File _file) { try { if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { File parentDir = _file.getParentFile(); if (!parentDir.exists()) { parentDir.mkdirs(); } FileOutputStream f = new FileOutputStream(_file); _bitmap.compress(Bitmap.CompressFormat.JPEG, 100, f); f.flush(); f.close(); } else { // todo: write to internal memory here??? } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Format File Size
import java.text.DecimalFormat; class Main { public static String formatFileSize(long size) { if (size <= 0) return "0"; final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" }; int digitGroups = (int) (Math.log10(size) / Math.log10(1024)); return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups]; } }
File Upload
//package com.softright.net; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import android.util.Log; import java.util.ArrayList; import java.util.List; abstract class MutilPartBody { public abstract void put(DataOutputStream os) throws Exception ; protected int length; protected byte[] bytes; public byte[] getBytes() { return bytes; } public int getLength() { return length; } } /** * * @author aroot * */ class MutilPartEntity { private static final String BOUNDARY = "---------7d4a6d158c9"; private String boundary = BOUNDARY; private List<MutilPartBody> bodyList; public MutilPartEntity() { this.boundary = BOUNDARY; } public MutilPartEntity(List<MutilPartBody> bodyList) { this.boundary = BOUNDARY; this.bodyList = bodyList; } public MutilPartEntity(String boundary, List<MutilPartBody> bodyList) { this.boundary = boundary; this.bodyList = bodyList; } public void addBody(MutilPartBody body) { if (bodyList == null) { bodyList = new ArrayList<MutilPartBody>(); } bodyList.add(body); } public List<MutilPartBody> getBodyList() { return bodyList; } public void setBodyList(List<MutilPartBody> bodyList) { this.bodyList = bodyList; } public String getBoundary() { return boundary; } public void setBoundary(String boundary) { this.boundary = boundary; } } class FileUpload { private static final String BOUNDARY = "---------7d4a6d158c9"; private static final String END = "--" + FileUpload.getBoundary() + "--\r\n"; protected static final String getBoundary() { return BOUNDARY; } public String doUpload(String targetURL, MutilPartEntity entity) throws Exception { if (targetURL == null || targetURL.length() <= 0 || !targetURL.startsWith("http")) { throw new Exception( "#doUpload(String targetURL, List<MutilPartBody> bodyList)# targetURL invalid, " + targetURL); } List<MutilPartBody> bodyList = entity.getBodyList(); if (bodyList == null || bodyList.size() <= 0) { throw new Exception( "#doUpload(String targetURL, List<MutilPartBody> bodyList)# bodyList is empty"); } HttpURLConnection conn = null; URL url = null; StringBuilder returnSb = new StringBuilder(); try { url = new URL(targetURL); } catch (MalformedURLException e) { } try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); } catch (IOException e) { } conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setReadTimeout(50000); conn.setConnectTimeout(50000); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); try { DataOutputStream dataOutputStream = new DataOutputStream( conn.getOutputStream()); for (int i = 0; i < bodyList.size(); i++) { dataOutputStream.writeBytes("--" + FileUpload.getBoundary()); dataOutputStream.writeBytes("\r\n"); MutilPartBody body = bodyList.get(i); body.put(dataOutputStream); if (i != bodyList.size()) { dataOutputStream.writeBytes("\r\n"); } } dataOutputStream.writeBytes(END); dataOutputStream.flush(); InputStream inputStream = conn.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader( inputStream)); String inputLine; while ((inputLine = in.readLine()) != null) { returnSb.append(inputLine); } dataOutputStream.close(); in.close(); } catch (IOException e) { } conn.disconnect(); return returnSb.toString(); } }
//package com.akjava.lib.android.util; import java.io.File; import android.net.Uri; public class FileNameUtils { public static String getExtension(File file){ return getExtension(file.getName()); } public static String getExtension(String name){ String ext; if(name.lastIndexOf(".")==-1){ ext=""; }else{ int index=name.lastIndexOf("."); ext=name.substring(index+1,name.length()); } return ext; } public static String getRemovedExtensionName(String name){ String baseName; if(name.lastIndexOf(".")==-1){ baseName=name; }else{ int index=name.lastIndexOf("."); baseName=name.substring(0,index); } return baseName; } public static File getChangedExtensionFile(File file,String extension,boolean overwrite){ File newFile=null; String baseName=null; if(file.getName().lastIndexOf(".")==-1){ baseName=file.getName(); }else{ int index=file.getName().lastIndexOf("."); baseName=file.getName().substring(0,index); } String bName=baseName; if(!extension.equals("")){ bName+="."+extension; } newFile=new File(file.getParent(),bName); int index=1; if(!overwrite){ while(newFile.exists()){ String specific="("+index+")"; String tmpName=baseName+specific; if(!extension.equals("")){ tmpName+="."+extension; } newFile=new File(file.getParent(),tmpName); index++; } } return newFile; } public static final String SCHME_FILE="file"; public static final String SCHME_FILE_AND_SEPARATOR="file://"; public static String uriToPath(Uri uri){ if(uri.getScheme().equals(SCHME_FILE)){ return uri.getPath(); } return null; } public static Uri pathToUri(String path){ return Uri.parse(SCHME_FILE_AND_SEPARATOR+path); } public static boolean isFileUri(String uri){ return uri!=null && uri.startsWith(SCHME_FILE_AND_SEPARATOR); } public static String uriToPath(String uri) { if(isFileUri(uri)){ return uri.substring(SCHME_FILE_AND_SEPARATOR.length()); } return null; } }
Write and append string to file
//package com.totsp.bookworm.util; import android.util.Log; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.nio.channels.FileChannel; /** * FileUtils. * * @author ccollins * */ final class FileUtil { // Object for intrinsic lock (per docs 0 length array "lighter" than a normal Object public static final Object[] DATA_LOCK = new Object[0]; private FileUtil() { } /** * Copy file. * * @param src * @param dst * @throws IOException */ public static void copyFile(final File src, final File dst) throws IOException { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } /** * Replace entire File with contents of String. * * @param fileContents * @param file * @return */ public static boolean writeStringAsFile(final String fileContents, final File file) { boolean result = false; try { synchronized (DATA_LOCK) { if (file != null) { file.createNewFile(); // ok if returns false, overwrite Writer out = new BufferedWriter(new FileWriter(file), 1024); out.write(fileContents); out.close(); result = true; } } } catch (IOException e) { // Log.e(Constants.LOG_TAG, "Error writing string data to file " + e.getMessage(), e); } return result; } /** * Append String to end of File. * * @param appendContents * @param file * @return */ public static boolean appendStringToFile(final String appendContents, final File file) { boolean result = false; try { synchronized (DATA_LOCK) { if (file != null && file.canWrite()) { file.createNewFile(); // ok if returns false, overwrite Writer out = new BufferedWriter(new FileWriter(file, true), 1024); out.write(appendContents); out.close(); result = true; } } } catch (IOException e) { // Log.e(Constants.LOG_TAG, "Error appending string data to file " + e.getMessage(), e); } return result; } }
//package edu.dhbw.andar.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.content.res.Resources; import android.content.res.Resources.NotFoundException; import android.text.GetChars; public class IO { /** * transfers required files to the the private file system part * in order to be access them from C Code. * required, as you can not access the files of the apk package directly */ public static void transferFilesToPrivateFS(File base, Resources res) throws IOException { AssetManager am = res.getAssets(); if (!base.exists()) { base.mkdir(); } if (base.exists()) { File cameraFile = new File(base, "camera_para.dat"); if (!cameraFile.exists()) { copy(am.open("camera_para.dat"), new FileOutputStream(cameraFile)); } } } /** * * @param base * @param assetFileName filename of the file in the assets folder * @param res * @throws IOException */ public static void transferFileToPrivateFS(File base, String assetFileName,Resources res) throws IOException { AssetManager am = res.getAssets(); if (!base.exists()) { base.mkdir(); } if (base.exists()) { File file = new File(base, assetFileName); if (!file.exists()) { copy(am.open(assetFileName), new FileOutputStream(file)); } } } static void copy( InputStream in, OutputStream out ) throws IOException { byte[] buffer = new byte[ 0xFFFF ]; for ( int len; (len = in.read(buffer)) != -1; ) out.write( buffer, 0, len ); } }
returns a canonical line of a obj or mtl file.
//package edu.dhbw.andobjviewer.parser; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; class Util { private static final Pattern trimWhiteSpaces = Pattern.compile("[\\s]+"); private static final Pattern removeInlineComments = Pattern.compile("#"); private static final Pattern splitBySpace = Pattern.compile(" "); /** * returns a canonical line of a obj or mtl file. * e.g. it removes multiple whitespaces or comments from the given string. * @param line * @return */ public static final String getCanonicalLine(String line) { line = trimWhiteSpaces.matcher(line).replaceAll(" "); if(line.contains("#")) { String[] parts = removeInlineComments.split(line); if(parts.length > 0) line = parts[0];//remove inline comments } return line; } }
Trims down obj files, so that they may be parsed faster later on.
//package edu.dhbw.andobjviewer.parser; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; class Util { private static final Pattern trimWhiteSpaces = Pattern.compile("[\\s]+"); private static final Pattern removeInlineComments = Pattern.compile("#"); private static final Pattern splitBySpace = Pattern.compile(" "); public static void trim(BufferedReader in, BufferedWriter out) throws IOException { String line; out.write("#trimmed\n"); for (line = in.readLine(); line != null; line = in.readLine()) { line = getCanonicalLine(line); if(line.length()>0) { out.write(line.trim()); out.write('\n'); } } in.close(); out.close(); } public static final String getCanonicalLine(String line) { line = trimWhiteSpaces.matcher(line).replaceAll(" "); if(line.contains("#")) { String[] parts = removeInlineComments.split(line); if(parts.length > 0) line = parts[0];//remove inline comments } return line; } }
class FileSizeFormatter { private static final String BYTES = "Bytes"; private static final String MEGABYTES = "MB"; private static final String KILOBYTES = "kB"; private static final String GIGABYTES = "GB"; private static final long KILO = 1024; private static final long MEGA = KILO * 1024; private static final long GIGA = MEGA * 1024; public static String formatFileSize(final long pBytes){ if(pBytes < KILO){ return pBytes + BYTES; }else if(pBytes < MEGA){ return (int)(0.5 + (pBytes / (double)KILO)) + KILOBYTES; }else if(pBytes < GIGA){ return (int)(0.5 + (pBytes / (double)MEGA)) + MEGABYTES; }else { return (int)(0.5 + (pBytes / (double)GIGA)) + GIGABYTES; } } }
Get File Contents as String
//package ca.skennedy.androidunusedresources; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; class FileUtilities { public static String getFileContents(final File file) throws IOException { final InputStream inputStream = new FileInputStream(file); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); final StringBuilder stringBuilder = new StringBuilder(); boolean done = false; while (!done) { final String line = reader.readLine(); done = (line == null); if (line != null) { stringBuilder.append(line); } } reader.close(); inputStream.close(); return stringBuilder.toString(); } }
Read File and return CharSequence
//package com.troubadorian.android.jukebox; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStreamReader; import android.app.Activity; class FileUtils { public static CharSequence readFile(Activity activity, int id) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(activity .getResources().openRawResource(id))); String line; StringBuilder buffer = new StringBuilder(); while ((line = in.readLine()) != null) { buffer.append(line).append('\n'); } // Chomp the last newline buffer.deleteCharAt(buffer.length() - 1); return buffer; } catch (IOException e) { return ""; } finally { closeStream(in); } } /** * Closes the specified stream. * * @param stream * The stream to close. */ private static void closeStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { // Ignore } } } }
Copy File
//package org.alexis.libstardict; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import android.os.Environment; class FileUtils { public static boolean copyFile(File source, File dest) { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(new FileInputStream(source)); bos = new BufferedOutputStream(new FileOutputStream(dest, false)); byte[] buf = new byte[1024]; bis.read(buf); do { bos.write(buf); } while(bis.read(buf) != -1); } catch (IOException e) { return false; } finally { try { if (bis != null) bis.close(); if (bos != null) bos.close(); } catch (IOException e) { return false; } } return true; } // WARNING ! Inefficient if source and dest are on the same filesystem ! public static boolean moveFile(File source, File dest) { return copyFile(source, dest) && source.delete(); } // Returns true if the sdcard is mounted rw public static boolean isSDMounted() { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } }
Read/write From FileSystem, browse Account
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; import android.app.Activity; import android.widget.ListView; class AccountFileUtil { public Properties readFromFS(Activity caller) { try{ Properties fileProps = new Properties(); File dir = caller.getApplicationContext().getFilesDir(); File input = new File(dir.getAbsolutePath() + "/preferences" ); fileProps.load(new FileInputStream(input)); return fileProps; } catch(Exception e){} return null; } public void writeFromFS(Activity caller){ try{ Properties props = new Properties(); props.put("clau","stronzo"); File dir = caller.getApplicationContext().getFilesDir(); File out = new File(dir.getPath() + "/preferences") ; props.put("location" , dir.getAbsolutePath()); props.save(new FileOutputStream(out), null); } catch(Exception e){} } public ListView browseAccount(Activity caller){ ListView map = new ListView(null); try{ File dir = caller.getApplicationContext().getFilesDir(); int i = 0; Properties props = new Properties(); while ( true) { props.load(new FileInputStream(dir.getAbsolutePath() + "/preferences" + i)); String account = (String)props.get("account"); //map.setite i++; } } catch(Exception e){} return map; } }
Create Path and file under External Storage
//package org.freemp3droid; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import android.content.Context; import android.os.Environment; class Util { public static final String DATE_STRING="yyyy-MM-dd-HH_mm_ss"; public static String createPath(String fileType,String suffix,Context ctx) { long dateTaken = System.currentTimeMillis(); File filesDir = getStorageDir(ctx); String filesDirPath = filesDir.getAbsolutePath(); filesDir.mkdirs(); SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_STRING); Date date = new Date(dateTaken); String filepart = dateFormat.format(date); String filename = filesDirPath + "/" + filepart + fileType + suffix; return filename; } //takes /mnt/sdcard/1/2/3/whatever.wav and returns /mnt/sdcard/convdir/whatever.mp3 public static String createMP3File(String orig,Context ctx) { File filesDir = getStorageDir(ctx); String filesDirPath = filesDir.getAbsolutePath(); String origFile = orig.substring(orig.lastIndexOf("/")); origFile = origFile.substring(0, origFile.lastIndexOf(".")); String filename = filesDirPath + "/" + origFile + ".mp3"; return filename; } public static File getStorageDir(Context ctx) { String filesDirPath = Environment.getExternalStorageDirectory().toString() +"/" + "convdir"; File ret = new File(filesDirPath); if(!ret.exists()) { ret.mkdirs(); } return ret; } public static ArrayList<File> listFiles(Context ctx) { ArrayList<File> ret = new ArrayList<File>(); File filesDir = getStorageDir(ctx); File[] list = filesDir.listFiles(); for(File f: list) { if(f.getAbsolutePath().endsWith(".mp3")) { ret.add(f); } } return ret; } }
Get File Extension Name
//package com.escobaro; import java.io.File; import java.text.DecimalFormat; import android.os.Debug; import android.util.Log; class Utilities { public static String TAG = "Utilities"; public static String getFileExtensionName(File f) { if (f.getName().indexOf(".") == -1) { return ""; } else { return f.getName().substring(f.getName().length() - 3, f.getName().length()); } } }
Extract File Name From String
//package com.escobaro; import java.io.File; import java.text.DecimalFormat; import android.os.Debug; import android.util.Log; class Utilities { public static String TAG = "Utilities"; public static String extractFileNameFromString(String fullFileName){ return fullFileName.substring(fullFileName.lastIndexOf("/")+1, fullFileName.length() ); } }
Write String to file
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import android.content.Context; import android.os.Environment; import android.util.Log; import android.widget.Toast; class FileUtilities { private Writer writer; private String absolutePath; private final Context context; public FileUtilities(Context context) { super(); this.context = context; } public void write(String fileName, String data) { File root = Environment.getExternalStorageDirectory(); File outDir = new File(root.getAbsolutePath() + File.separator + "EZ_time_tracker"); if (!outDir.isDirectory()) { outDir.mkdir(); } try { if (!outDir.isDirectory()) { throw new IOException( "Unable to create directory EZ_time_tracker. Maybe the SD card is mounted?"); } File outputFile = new File(outDir, fileName); writer = new BufferedWriter(new FileWriter(outputFile)); writer.write(data); Toast.makeText(context.getApplicationContext(), "Report successfully saved to: " + outputFile.getAbsolutePath(), Toast.LENGTH_LONG).show(); writer.close(); } catch (IOException e) { Log.w("eztt", e.getMessage(), e); Toast.makeText(context, e.getMessage() + " Unable to write to external storage.", Toast.LENGTH_LONG).show(); } } public Writer getWriter() { return writer; } public String getAbsolutePath() { return absolutePath; } }
Create an output file from raw resources.
//package ca.chaves.familyBrowser.helpers; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.content.Context; import android.content.res.Resources; import android.util.Log; class Utils { protected static final String TAG = Utils.class.getSimpleName(); public static void createFile(final String outputFile, final Context context, final Integer[] inputRawResources) throws IOException { final OutputStream outputStream = new FileOutputStream(outputFile); final Resources resources = context.getResources(); final byte[] largeBuffer = new byte[1024 * 4]; int totalBytes = 0; int bytesRead = 0; for (Integer resource : inputRawResources) { final InputStream inputStream = resources.openRawResource(resource .intValue()); while ((bytesRead = inputStream.read(largeBuffer)) > 0) { if (largeBuffer.length == bytesRead) { outputStream.write(largeBuffer); } else { final byte[] shortBuffer = new byte[bytesRead]; System.arraycopy(largeBuffer, 0, shortBuffer, 0, bytesRead); outputStream.write(shortBuffer); } totalBytes += bytesRead; } inputStream.close(); } outputStream.flush(); outputStream.close(); } }
//package com.google.doclava; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class JarUtils { public static JarFile jarForClass(Class<?> clazz, JarFile defaultJar) { String path = "/" + clazz.getName().replace('.', '/') + ".class"; URL jarUrl = clazz.getResource(path); if (jarUrl == null) { return defaultJar; } String url = jarUrl.toString(); int bang = url.indexOf("!"); String JAR_URI_PREFIX = "jar:file:"; if (url.startsWith(JAR_URI_PREFIX) && bang != -1) { try { return new JarFile(url.substring(JAR_URI_PREFIX.length(), bang)); } catch (IOException e) { throw new IllegalStateException("Error loading jar file.", e); } } else { return defaultJar; } } public static void copyResourcesToDirectory(JarFile fromJar, String jarDir, String destDir) throws IOException { for (Enumeration<JarEntry> entries = fromJar.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith(jarDir + "/") && !entry.isDirectory()) { File dest = new File(destDir + "/" + entry.getName().substring(jarDir.length() + 1)); File parent = dest.getParentFile(); if (parent != null) { parent.mkdirs(); } FileOutputStream out = new FileOutputStream(dest); InputStream in = fromJar.getInputStream(entry); try { byte[] buffer = new byte[8 * 1024]; int s = 0; while ((s = in.read(buffer)) > 0) { out.write(buffer, 0, s); } } catch (IOException e) { throw new IOException("Could not copy asset from jar file", e); } finally { try { in.close(); } catch (IOException ignored) {} try { out.close(); } catch (IOException ignored) {} } } } } private JarUtils() {} // non-instantiable }
Reads a file from /raw/res/ and returns it as a String
//package com.lexandera.mosembro.util; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Scanner; import android.content.res.Resources; public class Reader { public static String readRawString(Resources res, int resourceId) { StringBuilder sb = new StringBuilder(); Scanner s = new Scanner(res.openRawResource(resourceId)); while (s.hasNextLine()) { sb.append(s.nextLine() + "\n"); } return sb.toString(); } public static byte[] readRawByteArray(Resources res, int resourceId) { InputStream is = null; byte[] raw = new byte[] {}; try { is = res.openRawResource(resourceId); raw = new byte[is.available()]; is.read(raw); } catch (IOException e) { e.printStackTrace(); raw = null; } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return raw; } public static String readRemoteString(String fileUrl) { StringBuilder sb = new StringBuilder(); try { URLConnection connection = (new URL(fileUrl)).openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.connect(); Scanner s = new Scanner(connection.getInputStream()); while (s.hasNextLine()) { sb.append(s.nextLine() + "\n"); } } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } public static byte[] readRemoteByteArray(String fileUrl) { InputStream is = null; byte[] raw = new byte[] {}; try { URLConnection connection = (new URL(fileUrl)).openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.connect(); is = connection.getInputStream(); raw = new byte[is.available()]; is.read(raw); } catch (Exception e) { e.printStackTrace(); raw = null; } finally { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } return raw; } }
Read Config ini file
//package com.pinpoint.util; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class Config { private Properties configuration; private String configurationFile = "config.ini"; public Config() { configuration = new Properties(); } public boolean load() { boolean retval = false; try { configuration.load(new FileInputStream(this.configurationFile)); retval = true; } catch (IOException e) { System.out.println("Configuration error: " + e.getMessage()); } return retval; } public boolean store() { boolean retval = false; try { configuration.store(new FileOutputStream(this.configurationFile), null); retval = true; } catch (IOException e) { System.out.println("Configuration error: " + e.getMessage()); } return retval; } public void set(String key, String value) { configuration.setProperty(key, value); } public String get(String key) { return configuration.getProperty(key); } }
Read Write File Manager
//package com.application.esmaker.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import android.content.Context; import android.util.Log; import android.widget.Toast; public class ReadWriteFileManager { public void start(Context cx) { final String TEMP_FILE_NAME = "temp.txt"; String contentToWrite = "THIS IS THE CONTENT TO WRITE!"; Log.d("DEBUG", "Instantiating ReadWriteManager.."); ReadWriteFileManager readWriteFileManager = new ReadWriteFileManager(); Log.d("DEBUG", "Writing to file..."); readWriteFileManager.writeToFile(cx, contentToWrite.getBytes(), TEMP_FILE_NAME); Log.d("DEBUG", "Reading from file.."); String contentRead = readWriteFileManager.readFromFile(cx, TEMP_FILE_NAME); Log.d("DEBUG", "Content read: " + contentRead); Toast.makeText(cx, contentRead, Toast.LENGTH_LONG).show(); } public String readFromFile(Context context, String sourceFileName) { FileInputStream fis = null; InputStreamReader isr = null; char[] inputBuffer = null; String file_content = null; try { // As this requires full path of the file... // i.e data/data/package_name/files/your_file_name File sourceFile = new File(context.getFilesDir().getPath() + File.separator + sourceFileName); if (sourceFile.exists()) { // Probably you will get an exception if its // a huge content file.. // I suggest you to handle content here // itself, instead of // returning it as return value.. inputBuffer = new char[(int) sourceFile.length()]; fis = context.openFileInput(sourceFileName); isr = new InputStreamReader(fis); isr.read(inputBuffer); file_content = new String(inputBuffer); try { isr.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); file_content = null; } return file_content; } public boolean writeToFile(Context context, byte[] contentToWrite, String destinationFileName) { FileOutputStream fos = null; boolean retValue = false; try { // Note that your file will be created and stored // under the path: data/data/your_app_package_name/files/ fos = context.openFileOutput(destinationFileName, Context.MODE_PRIVATE); // Note that we are not buffering of contents to write.. // So, this will work best for files with less content.... fos.write(contentToWrite); // Successfully completed writing.. retValue = true; try { fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { // You can catch exceptions specifically for low mem, // file cant be created, and so on.. e.printStackTrace(); // Failed to write.. retValue = false; } return retValue; } }
Copy two files
//package net.eclipseforum.id3tagman.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; class FileCopy { public static void main(String[] args) { try { copy("fromFile.txt", "toFile.txt"); } catch (IOException e) { System.err.println(e.getMessage()); } } public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader( System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); // write } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } }
Get the filename of the media file and use that as the default title
import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.util.Log; class Utils { public static String getFilePath(Context ctx, Uri uri) { ContentResolver cr = ctx.getContentResolver(); String file_path = null; // . Cursor cursor = cr.query(uri, new String[] { android.provider.MediaStore.MediaColumns.DATA }, null, null, null); if (cursor != null) { cursor.moveToFirst(); file_path = cursor.getString(0); cursor.close(); } else { file_path = uri.getPath(); } return file_path; } }
Copy File and Directory
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; class Util { public static void copyDirectory(File sourceLocation, File targetLocation) throws IOException { if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) { targetLocation.mkdirs(); } String[] children = sourceLocation.list(); for (int i = 0; i < children.length; i++) { copyDirectory(new File(sourceLocation, children[i]), new File( targetLocation, children[i])); } } else { copyFile(sourceLocation, targetLocation); } } /** * @param sourceLocation * @param targetLocation * @throws FileNotFoundException * @throws IOException */ public static void copyFile(File sourceLocation, File targetLocation) throws FileNotFoundException, IOException { InputStream in = new FileInputStream(sourceLocation); OutputStream out = new FileOutputStream(targetLocation); // Copy the bits from instream to outstream byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } static public boolean deleteDirectory(File path) { if (path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return (path.delete()); } }
public class MimeUtils { public static String getType(final String filename) { int pos = filename.lastIndexOf('.'); if (pos != -1) { String ext = filename.substring(filename.lastIndexOf('.') + 1, filename.length()); if (ext.equalsIgnoreCase("mp3")) return "audio/mpeg"; if (ext.equalsIgnoreCase("aac")) return "audio/aac"; if (ext.equalsIgnoreCase("wav")) return "audio/wav"; if (ext.equalsIgnoreCase("ogg")) return "audio/ogg"; if (ext.equalsIgnoreCase("mid")) return "audio/midi"; if (ext.equalsIgnoreCase("midi")) return "audio/midi"; if (ext.equalsIgnoreCase("wma")) return "audio/x-ms-wma"; if (ext.equalsIgnoreCase("mp4")) return "video/mp4"; if (ext.equalsIgnoreCase("avi")) return "video/x-msvideo"; if (ext.equalsIgnoreCase("wmv")) return "video/x-ms-wmv"; if (ext.equalsIgnoreCase("png")) return "image/png"; if (ext.equalsIgnoreCase("jpg")) return "image/jpeg"; if (ext.equalsIgnoreCase("jpe")) return "image/jpeg"; if (ext.equalsIgnoreCase("jpeg")) return "image/jpeg"; if (ext.equalsIgnoreCase("gif")) return "image/gif"; if (ext.equalsIgnoreCase("xml")) return "text/xml"; if (ext.equalsIgnoreCase("txt")) return "text/plain"; if (ext.equalsIgnoreCase("cfg")) return "text/plain"; if (ext.equalsIgnoreCase("csv")) return "text/plain"; if (ext.equalsIgnoreCase("conf")) return "text/plain"; if (ext.equalsIgnoreCase("rc")) return "text/plain"; if (ext.equalsIgnoreCase("htm")) return "text/html"; if (ext.equalsIgnoreCase("html")) return "text/html"; if (ext.equalsIgnoreCase("pdf")) return "application/pdf"; if (ext.equalsIgnoreCase("apk")) return "application/vnd.android.package-archive"; // Additions and corrections are welcomed. } return "*/*"; } }
//package net.vexelon.bgrates; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.net.URL; import java.net.URLConnection; import org.apache.http.util.ByteArrayBuffer; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.KeyEvent; public class Utils { /** * Move a file stored in the cache to the internal storage of the specified context * @param context * @param cacheFile * @param internalStorageName */ public static boolean moveCacheFile(Context context, File cacheFile, String internalStorageName) { boolean ret = false; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(cacheFile); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int read = -1; while( (read = fis.read(buffer) ) != -1 ) { baos.write(buffer, 0, read); } baos.close(); fis.close(); fos = context.openFileOutput(internalStorageName, Context.MODE_PRIVATE); baos.writeTo(fos); fos.close(); // delete cache cacheFile.delete(); ret = true; } catch(Exception e) { //Log.e(TAG, "Error saving previous rates!"); } finally { try { if ( fis != null ) fis.close(); } catch (IOException e) { } try { if ( fos != null ) fos.close(); } catch (IOException e) { } } return ret; } }
CharSequence from File
//package com.retain; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.Date; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.Log; import android.widget.ImageView; import android.widget.Toast; /** * @author Nazmul Idris * @version 1.0 * @since Jul 8, 2008, 2:35:39 PM */ class AppUtils { /** * 127.0.0.1 in the emulator points back to itself. Use this if you want to * access your host OS */ public static String EmulatorLocalhost = "10.0.2.2"; public static CharSequence fromFile(String filename) throws IOException { FileInputStream fis = new FileInputStream(filename); FileChannel fc = fis.getChannel(); // Create a read-only CharBuffer on the file ByteBuffer bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int) fc.size()); CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf); return cbuf; } }// end class AppUtils
File Manager
//package com.swm.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; public class FileManager { static FileManager fileMgr = null; public static FileManager getInstance() { if ( fileMgr == null ){ fileMgr = new FileManager(); } return fileMgr; } public String readFile( String filePath, String fileName ) { StringBuffer contents = new StringBuffer(); File inputFile = new File( filePath + fileName ); if ( !inputFile.exists() ) { System.out.println( "[FILE READ ERROR] FILE NOT EXIST"); return ""; } FileInputStream fis = null; try { fis = new FileInputStream( inputFile ); int c; while ((c = fis.read()) != -1) contents.append((char) c); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println( e.getMessage() ); } catch (IOException e) { e.printStackTrace(); System.out.println( e.getMessage() ); } finally { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return contents.toString(); /* StringBuffer sb = new StringBuffer(); BufferedReader rd; try { rd = new BufferedReader( new FileReader(new File(filePath + fileName))); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); */ } public String normalizeContents( String content ) { StringBuffer sb = new StringBuffer(); for ( int i = 0 ; i < content.length() ; i++ ){ char ch = content.charAt(i); if ( ch != ' ' && ch != '\n' && ch != '\t' && ch != '\r' ){ sb.append( ch ); } } return sb.toString(); } public void writeFile( String filePath, String fileName, String contents ) { FileWriter writer = null; BufferedWriter bufferWriter = null; try { writer = new FileWriter(filePath + fileName); bufferWriter = new BufferedWriter(writer); bufferWriter.write(contents); bufferWriter.flush(); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } finally { try { bufferWriter.close(); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void copyFile(String srcFilePath, String srcFileName, String destFilePath, String destFileName) { if ( destFileName.equals( "" ) ) destFileName = srcFileName; String contents = readFile( srcFilePath, srcFileName ); writeFile( destFilePath, destFileName, contents ); System.out.println( "[COPY] " + srcFilePath + srcFileName + " -->> " + destFilePath + destFileName ); } public void copyDirectory(String srcFilePath, String destFilePath ) { File srcDir = new File( srcFilePath ); if ( srcDir.exists() && srcDir.isDirectory() ) { File destDir = new File( destFilePath ); if ( !destDir.exists() ) { if ( !destDir.mkdirs() ) return; System.out.println( "[COPY][MKDIR] MAKE DESTINATION DIR = " + destFilePath ); } File[] fileList = srcDir.listFiles(); for( File file : fileList ) { if ( file.getName().contains( ".svn") ) continue; String contents = readFile( srcFilePath, file.getName() ); writeFile( destFilePath, file.getName(), contents ); System.out.println( "[COPY] " + srcFilePath + file.getName() + " -->> " + destFilePath + file.getName() ); } } else { System.out.println( "[COPY][ERROR] SRC Directory is not Exist : " + srcFilePath ); } } public void replaceContents(String filePath, String fileName, String findStr, String replaceStr ) { String contents = readFile( filePath, fileName ); if ( contents.contains( findStr )) { contents = contents.replaceAll( findStr, replaceStr ); FileManager.getInstance().writeFile( filePath, fileName, contents ); System.out.println( "[REPLACE CONTENT]["+ filePath+fileName +"] [" + findStr + "] >>> [" + replaceStr + "] " ); } } public void insertBeforeContents( String filePath, String fileName, String beforeStr, String addStr ){ String contents = readFile( filePath, fileName ); if ( !contents.contains( addStr )) { int insertPos; if ( ( insertPos = contents.indexOf( beforeStr )) >= 0 ) { StringBuffer sb = new StringBuffer( contents.substring(0, insertPos-1) ); sb.append( addStr ); sb.append( contents.substring( insertPos, contents.length())); FileManager.getInstance().writeFile( filePath, fileName, sb.toString() ); System.out.println( "[INSERT-BEFORE-CONTENT]["+ filePath+fileName +"] = " + addStr ); } } } public void insertAfterContents( String filePath, String fileName, String afterStr, String addStr ){ String contents = readFile( filePath, fileName ); if ( !contents.contains( addStr )) { int insertPos; if ( ( insertPos = contents.indexOf( afterStr )) >= 0 ) { StringBuffer sb = new StringBuffer( contents.substring(0, insertPos + afterStr.length() ) ); sb.append( addStr ); sb.append( contents.substring( insertPos + afterStr.length(), contents.length())); FileManager.getInstance().writeFile( filePath, fileName, sb.toString() ); System.out.println( "[INSERT-AFTER-CONTENT]["+ filePath+fileName +"] = " + addStr ); } } } }
Save Exception to a file
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import android.os.Environment; import android.util.Log; class Main { private static final String TAG = "Tag"; private static final String DIRECTORY_SEPARATOR = System.getProperty("file.separator"); public static void ToFile(Exception exception) { String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(System .currentTimeMillis()); File dirFile = new File(Environment.getExternalStorageDirectory() + DIRECTORY_SEPARATOR + "WiMAXNotifier" + DIRECTORY_SEPARATOR + "logs" + DIRECTORY_SEPARATOR); dirFile.mkdirs(); File file = new File(dirFile, "wmnTrace_" + timestamp + ".stack"); FileOutputStream fileOutputStream = null; try { String stackString = Log.getStackTraceString(exception); if (stackString.length() > 0) { file.createNewFile(); fileOutputStream = new FileOutputStream(file); fileOutputStream.write(stackString.getBytes()); fileOutputStream.flush(); fileOutputStream.close(); } } catch (FileNotFoundException fileNotFoundException) { Log.e("TAG", "File not found!", fileNotFoundException); } catch (IOException ioException) { Log.e("TAG", "Unable to write to file!", ioException); } return; } }
Delete a file and create directory
//package org.beryl.io; import java.io.File; public class FileUtils { public static boolean delete(String path) { final File deleteTarget = new File(path); return delete(deleteTarget); } public static boolean delete(File targetFile) { boolean deleted = true; try { deleted = targetFile.delete(); if(!deleted && ! targetFile.isFile()) { throw new Exception(String.format("File could not be deleted. Path: %s", targetFile.getAbsolutePath())); } deleted = true; } catch (Exception e) { deleted = false; } return deleted; } public static boolean createDirectory(File directory) { boolean created = true; try { created = directory.mkdirs(); if(!created && ! directory.isDirectory()) { throw new Exception(String.format("Directory could not be created. Path: %s", directory.getAbsolutePath())); } created = true; } catch (Exception e) { created = false; } return created; } }
Get a list of filenames in this folder.
//package org.shadowlands.roadtrip.android.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Collections; import java.util.regex.PatternSyntaxException; public class FileUtils { public static ArrayList<String> getFileNames (final String folder, final String fileNameFilterPattern, final int sort) throws PatternSyntaxException { ArrayList<String> myData = new ArrayList<String>(); File fileDir = new File(folder); if(!fileDir.exists() || !fileDir.isDirectory()){ return null; } String[] files = fileDir.list(); if(files.length == 0){ return null; } for (int i = 0; i < files.length; i++) { if(fileNameFilterPattern == null || files[i].matches(fileNameFilterPattern)) myData.add(files[i]); } if (myData.size() == 0) return null; if (sort != 0) { Collections.sort(myData, String.CASE_INSENSITIVE_ORDER); if (sort < 0) Collections.reverse(myData); } return myData; } public static boolean copyFile (String fromFilePath, String toFilePath, final boolean overwriteExisting) throws IOException { try{ File fromFile = new File(fromFilePath); File toFile = new File(toFilePath); if(overwriteExisting && toFile.exists()) toFile.delete(); return copyFile(fromFile, toFile); } catch(SecurityException e){ return false; } } public static boolean copyFile(File source, File dest) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); if (in != null) in.close(); if (out != null) out.close(); return true; } catch(IOException e){ try { if (in != null) in.close(); } catch (IOException e2) {} try { if (out != null) out.close(); } catch (IOException e2) {} throw e; } } }
Delete Directory
import java.io.File; class FileUtils { static public boolean deleteDirectory(File path) { if (path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return (path.delete()); } static void deleteIfExists(File file) { if (file != null) { if (file.exists() == true) { file.delete(); } } } }
Delete Directory 2
import java.io.File; class DirectoryUtils { public static void deleteDirectory(File directory) { if (!directory.isDirectory()) return; File[] content = directory.listFiles(); for (int f = 0; f < content.length; f++) { File file = content[f]; if (file.isDirectory()) deleteDirectory(file); else file.delete(); } directory.delete(); } }
Delete Directory 3
//package net.bible.service.common; import java.io.File; // class CommonUtils { static public boolean deleteDirectory(File path) { if (path.exists()) { if (path.isDirectory()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } boolean deleted = path.delete(); if (!deleted) { } return deleted; } return false; } }
Get readable folder size
//package cn.syncbox.client; import java.io.File; import java.net.HttpURLConnection; import java.text.DecimalFormat; import android.webkit.MimeTypeMap; class Utils { public static String[] formatSize(long bytes, int place) { int level = 0; float number = bytes; String[] unit = { "bytes", "KB", "MB", "GB", "TB", "PB" }; while (number >= 1024f) { number /= 1024f; level++; } String formatStr = null; if (place == 0) { formatStr = "###0"; } else { formatStr = "###0."; for (int i = 0; i < place; i++) { formatStr += "#"; } } DecimalFormat nf = new DecimalFormat(formatStr); String[] value = new String[2]; value[0] = nf.format(number); value[1] = unit[level]; return value; } public static long getFolderSize(File folderPath) { long totalSize = 0; if (folderPath == null) { return 0; } if (!folderPath.isDirectory()) { return 0; } File[] files = folderPath.listFiles(); for (File file : files) { if (file.isFile()) { totalSize += file.length(); } else if (file.isDirectory()) { totalSize += file.length(); totalSize += getFolderSize(file); } } return totalSize; } public static void clearFolder(File folderPath) { if (folderPath == null) { return; } if (!folderPath.isDirectory()) { return; } File[] files = folderPath.listFiles(); for (File file : files) { if (file.isFile()) { file.delete(); } else if (file.isDirectory()) { clearFolder(file); file.delete(); } } } public static String getExtension(String uri) { if (uri == null) { return null; } int dot = uri.lastIndexOf("."); if (dot >= 0) { // A file extension without the leading '.' return uri.substring(dot).substring(1); } else { // No extension. return ""; } } public static String getMimeType(String fullname) { if (fullname == null) { return null; } String type = HttpURLConnection.guessContentTypeFromName(fullname); if (type == null) { String ext = Utils.getExtension(fullname); type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext); } // default if (type == null) { type = "application/octet-stream"; } return type; } }
Copy chars from a large (over 2GB) Reader to a Writer.
import java.io.IOException; import java.io.Reader; import java.io.Writer; class Main { private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; public static long copyLarge(Reader input, Writer output) throws IOException { char[] buffer = new char[DEFAULT_BUFFER_SIZE]; long count = 0; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } }