[Java]
Package com. xiazdong. file. util;
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 android. content. Context;
Import android. OS. Environment;
Public class FileUtil {
/**
* Save text to memory
* @ Param context
* @ Param filename
* @ Param content
* @ Param mode
* @ Throws Exception
*/
Public static void saveTextInMemory (Context context, String filename, String content, int mode) throws Exception {
Try {
FileOutputStream out = context. openFileOutput (filename, mode );
Out. write (content. getBytes ("UTF-8 "));
Out. close ();
}
Catch (Exception e ){
Throw new Exception ();
}
}
/**
* Save the file to sdcard.
* @ Param filename
* @ Param content
* @ Throws Exception
*/
Public static void saveTextInSdcard (String filename, String content) throws Exception {
Try {
File f = new File (Environment. getExternalStorageDirectory (), filename );
FileOutputStream out = new FileOutputStream (f );
Out. write (content. getBytes ("UTF-8 "));
Out. close ();
}
Catch (Exception e ){
Throw new Exception ();
}
}
/**
* Reading files from memory
* @ Param filename
* @ Return
* @ Throws Exception
*/
Public static String loadTextFromSdcard (String filename) throws Exception {
Try {
File f = new File (Environment. getExternalStorageDirectory (), filename );
FileInputStream in = new FileInputStream (f );
Byte [] data = read2byte (in );
Return new String (data, "UTF-8 ");
}
Catch (Exception e ){
Throw new Exception ();
}
}
/**
* Reading files from sdcard
* @ Param context
* @ Param filename
* @ Return
* @ Throws Exception
*/
Public static String loadTextFromMemory (Context context, String filename) throws Exception {
Try {
FileInputStream in = context. openFileInput (filename );
Byte [] data = read2byte (in );
Return new String (data, "UTF-8 ");
}
Catch (Exception e ){
Throw new Exception ();
}
}
Private static byte [] read2byte (InputStream in) throws IOException {
Byte [] data;
ByteArrayOutputStream bout = new ByteArrayOutputStream ();
Byte [] buf = new byte [1, 1024];
Int len = 0;
While (len = in. read (buf ))! =-1 ){
Bout. write (buf, 0, len );
}
Data = bout. toByteArray ();
Return data;
}
}
Test code:
[Java]
FileUtil. saveTextInSdcard ("1.txt"," hello "); // save" hello "to/mnt/sdcard/1.txt
String content = FileUtil. loadTextFromSdcard ("1.txt"); // read/mnt/sdcard/1.txt content
FileUtil. saveTextInMemory (MainActivity. this, "1.txt"," hello ", Context. MODE_PRIVATE); // save hello to/data/package/files/1.txt
String content = FileUtil. loadTextFromMemory (MainActivity. this, "1.txt"); // read/data/package/files/1.txt content
Author: xiazdong