您的位置:首页 > 移动开发 > Android开发

android将一个String保存到.txt文本中

2013-07-10 20:06 120 查看
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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐