純粹是個(gè)人學(xué)習(xí)總結(jié),如有不對(duì)的地方請(qǐng)吐槽。
一、資源文件的讀?。?/p>
從resource的raw中讀取文件數(shù)據(jù):
String res = "";
try{
//得到資源中的Raw數(shù)據(jù)流
InputStream in = getResources().openRawResource(R.raw.test);
//得到數(shù)據(jù)的大小
int length = in.available();
byte [] buffer = new byte[length];
//讀取數(shù)據(jù)
in.read(buffer);
//依test.txt的編碼類型選擇合適的編碼,如果不調(diào)整會(huì)亂碼
res = EncodingUtils.getString(buffer, "BIG5");
//關(guān)閉
in.close();
}catch(Exception e){
e.printStackTrace();
}從resource的asset中讀取文件數(shù)據(jù)
String fileName = "test.txt"; //文件名字
String res="";
try{
//得到資源中的asset數(shù)據(jù)流
InputStream in = getResources().getAssets().open(fileName);
int length = in.available();
byte [] buffer = new byte[length];
in.read(buffer);
in.close();
res = EncodingUtils.getString(buffer, "UTF-8");
}catch(Exception e){
e.printStackTrace();
}
二、讀寫/data/data/<應(yīng)用程序名>目錄上的文件
//寫數(shù)據(jù)
public void writeFile(String fileName,String writestr) throws IOException{
try{
FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);
byte [] bytes = writestr.getBytes();
fout.write(bytes);
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
//讀數(shù)據(jù)
public String readFile(String fileName) throws IOException{
String res="";
try{
FileInputStream fin = openFileInput(fileName);
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
}
catch(Exception e){
e.printStackTrace();
}
return res;
}
三、讀寫SD卡中的文件。也就是/mnt/sdcard/目錄下面的文件
//寫數(shù)據(jù)到SD中的文件
public void writeFileSdcardFile(String fileName,String write_str) throws IOException{
try{
FileOutputStream fout = new FileOutputStream(fileName);
byte [] bytes = write_str.getBytes();
fout.write(bytes);
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
//讀SD中的文件
public String readFileSdcardFile(String fileName) throws IOException{
String res="";
try{
FileInputStream fin = new FileInputStream(fileName);
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
}
catch(Exception e){
e.printStackTrace();
}
return res;
}
四、使用File類進(jìn)行文件的讀寫
//讀文件
public String readSDFile(String fileName) throws IOException {
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
int length = fis.available();
byte [] buffer = new byte[length];
fis.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fis.close();
return res;
}
//寫文件
public void writeSDFile(String fileName, String write_str) throws IOException{
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file);
byte [] bytes = write_str.getBytes();
fos.write(bytes);
fos.close();
}
參考地址:http://blog.csdn.net/ztp800201/article/details/7322110