TXT文本的编码方式有UNICODES,UTF8,UTF16等等。 这里只针对UTF8编码的TXT文本作为例子。保存该txt文本到SD卡的download目录。
private boolean saveText(String text, String name) {
if(text == null) return false;
byte[] data = text.getBytes("UTF8");
if(null == data || data.length == 0){
return false;
}
FileOutputStream fout = null;
try {
String downloadDirectoryString = MmsConfig.DIRECTORY_DOWNLOADS_UNKNOW_TYPE;
// Depending on the location, there may be an
// extension already on the name or not
String dir = Environment.getExternalStorageDirectory() + "/"
+ downloadDirectoryString + "/";
String extension = ".txt";
File file = dir + name + extension;
// make sure the path is valid and directories created for this file.
File parentFile = file.getParentFile();
if (!parentFile.exists() && !parentFile.mkdirs()) {
return false;
}
fout = new FileOutputStream(file);
int size = data.length;
//UTF8 TEXT HEAD
byte[] heads = new byte[3];
heads[0] = (byte)(-17);
heads[1] = (byte)(-69);
heads[2] = (byte)(-65);
fout.write(heads, 0, heads.length);
fout.write(data, 0, size);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(file)));
} catch (IOException e) {
// Ignore
Log.e(TAG, "IOException caught while opening or reading stream", e);
return false;
} finally {
if (null != fout) {
try {
fout.close();
} catch (IOException e) {
// Ignore
Log.e(TAG, "IOException caught while closing stream", e);
return false;
}
}
}
return true;
}