Android 读写文件的N种写法(待续。。。)
读取raw文件
// 读取raw文件
private void rawRead(){
String ret = "";
try {
InputStream is = getResources().openRawResource(R.raw.my_raw);
int len = is.available();
byte []buffer = new byte[len];
is.read(buffer);
ret = EncodingUtils.getString(buffer, "utf-8");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
tvTXT.setText(ret);
}
读取assets文件
// 读取assets文件
private void assetsRead(){
String fileName = "my_assets.txt"; // assets下文件
// String fileName = "test/my_assets_test.txt"; // assets下子目录文件
String ret = "";
try {
InputStream is = getResources().getAssets().open(fileName);
int len = is.available();
byte []buffer = new byte[len];
is.read(buffer);
ret = EncodingUtils.getString(buffer, "utf-8");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
tvTXT.setText(ret);
}
读取sdcard文件
// 读取sdcard文件
private void sdcardRead(){
String fileName = "/sdcard/my_sdcard.txt"; // assets下文件
// String fileName = "/sdcard/test/my_sdcard_test.txt"; // sdcard下子目录文件
String ret = "";
try {
FileInputStream fis = new FileInputStream(fileName);
int len = fis.available();
byte []buffer = new byte[len];
fis.read(buffer);
ret = EncodingUtils.getString(buffer, "UTF-8");
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
tvTXT.setText(ret);
}
运行效果:
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有