一、读取assets目录下的文件
try {
InputStream is = getResources().getAssets().open("asset.txt");
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String str_asset = "";
while ((str_asset = br.readLine()) != null) {
Log.d("MainActivity", str_asset);
}
} catch (IOException e) {
e.printStackTrace();
}
二、读取raw目录下的文件
try {
InputStream is = getResources().openRawResource(R.raw.raw);
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String str_raw = "";
while ((str_raw = br.readLine()) != null) {
Log.d("MainActivity", str_raw);
}
} catch (IOException e) {
e.printStackTrace();
}
三、读取手机存储文件(内置)
try {
FileInputStream fis = openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis, "utf-8");
char input[] = new char[fis.available()];
isr.read(input);
isr.close();
fis.close();
String readed = new String(input);
show_text.setText(readed);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
四、写入到手机存储(内置)
try {
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
osw.write(mText.getText().toString());
osw.flush();
fos.flush();
osw.close();
fos.close();
Toast.makeText(MainActivity.this, "写入完成", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
五、读取SDCARD存储文件
File myfile = new File(sdcard, "This is my file.txt");
if (myfile.exists()) {
try {
FileInputStream fis = new FileInputStream(myfile);
InputStreamReader isr = new InputStreamReader(fis, "utf-8");
char input[] = new char[fis.available()];
isr.read(input);
String str = new String(input);
show_text_out.setText(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
六、写入SDCARD存储
File myFile = new File(sdcard, "This is my file.txt");
if (!sdcard.exists()) {
Toast.makeText(MainActivity.this, "当前系统不具备SD卡目录", Toast.LENGTH_SHORT).show();
return;
}
try {
myFile.createNewFile();
Toast.makeText(MainActivity.this, "文件创建完成", Toast.LENGTH_SHORT).show();
FileOutputStream fos = new FileOutputStream(myFile);
OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
osw.write(text_out.getText().toString());
osw.flush();
fos.flush();
osw.close();
fos.close();
Toast.makeText(MainActivity.this, "文件已经写入完成", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Github地址:https://github.com/wuyinlei/AndroidFileOperator