读取Assets中的文件数据
InputStream is = getResources().getAssets()
.open("读取的文件名");
InputStreamReader isr = new InputStreamReader(is,"utf-8");
BufferedReader bf = new BufferedReader(isr);
String string="";
while ((string = bf.readLine()) != null) {
System.out.println(string);
}
读取raw中的文件数据
InputStream is = getResources().openRawResource(R.raw.读取的文件名);
InputStreamReader isr = new InputStreamReader(is,"utf-8");
BufferedReader bf = new BufferedReader(isr);
String string="";
while ((string = bf.readLine()) != null) {
System.out.println(string);
}
写入外部存储文件
//获取SD卡根路径
File sdPath = Environment.getExternalStorageDirectory();
File file = new File(sdPath, "我的文件.txt");
//如果不存在SD卡,则不写入
if(!sdPath.exists()){
Toast.makeText(MainActivity.this, "无SD卡", Toast.LENGTH_SHORT).show();
}else{
try {
//如果文件夹不存在则创建
if(!file.exists()){
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
osw.write("我是内容");
osw.flush();
fos.flush();
osw.close();
fos.close();
Toast.makeText(MainActivity.this, "已创建", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
读取外部存储文件
//获取SD卡根路径
File sdPath = Environment.getExternalStorageDirectory();
File file = new File(sdPath, "我的文件.txt");
try {
//如果文件存在则读取
if(file.exists()){
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "utf-8");
char[] buf = new char[fis.available()];
isr.read(buf);
isr.close();
fis.close();
String string = new String(buf);
Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}