FileInputStream和FileOutputStream 是一對繼承與InputStream和OutputStream的類,分別用來創建磁盤文件的輸入流和輸出流對象,開發中我們會經常需要使用FileInputStream和FileOutputStream來實現本地文件讀寫操作,下面分享一個本地文件讀寫類
package com.pumasoft.vr.utils;
import android.content.Context;
import org.apache.http.util.EncodingUtils;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 本地文件讀寫類
* Created by lijuan on 2016/8/26.
*/
public class FileUtils {
/**
* 寫數據
*
* @param mContext 上下文
* @param fileName 文件名
* @param writestr 寫入文件的字符串
* @throws IOException
*/
public static void writeFile(Context mContext, String fileName, String writestr) throws IOException {
try {
//創建流文件寫出類
FileOutputStream fout = mContext.openFileOutput(fileName, Context.MODE_PRIVATE);
//獲取流的字符數
byte[] bytes = writestr.getBytes();
//寫出流,保存在文件fileName中
fout.write(bytes);
//關閉流
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 讀數據
*
* @param mContext 上下文
* @param fileName 文件名
* @return
* @throws IOException
*/
public static String readFile(Context mContext, String fileName) throws IOException {
String res = "";
try {
//創建流文件讀入類
FileInputStream fin = mContext.openFileInput(fileName);
//通過available方法取得流的最大字符數
byte[] buffer = new byte[fin.available()];
//讀入流,保存在byte數組
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
//關閉流
fin.close();
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
}
(一)主要步驟:
- 生成文件流對象:對文件讀操作時創建FileInputStream類對象,對文件寫操作時創建FileOutputStream類對象;
- 調用FileinputStream或fileoutputStream中方法:如read(buffer)、write(int buffer)方法來讀寫文件內容;
- 關閉文件流關閉文件;
(二)其中注意的是,在這裏我導入import org.apache.http.util.EncodingUtils;
出錯了
提示的錯誤是:程序包org.apache.http.util不存在,錯誤:找不到符號 符號:變量 EncodingUtils
還注:某些輸入文件使用或覆蓋了已過時的API,這是因爲這裏引用的EncodingUtils是HttpCore裏面的,你的build.gradle裏面沒有依賴這個包,解決辦法是在build.gradle文件添加依賴包:
compile 'org.apache.httpcomponents:httpcore:4.4.4'
(三)簡單的方法調用
1、調用寫數據的方法:
try {
FileUtils.writeFile(activity,"json.txt","寫入文件的字符串");
} catch (IOException e) {
e.printStackTrace();
}
2、讀數據
try {
String result = FileUtils.readFile(activity,"json.txt");
} catch (IOException e) {
e.printStackTrace();
}
好了,本篇文章就這樣子啦,存在不對的地方還望指導,感謝^_^