android 读写txt文件

来源:互联网 发布:网络女神排行 编辑:程序博客网 时间:2024/05/17 01:16

写了两个函数,发现调用时老是异常,原来是openFileOutput 方法必须在Activity中调用。所以一下两个函数都必须在Activity中调用。

public class FileStream{
private Context context;

public FileStream(Context context) {    this.context = context;}/** *  *@Title:SaveFile *@param fileName 需要加后缀,如.txt *@param fileContent *@throws IOException *@Description: 保存文件 */public void SaveFileTxt(String fileName, String fileContent)  { try{       FileOutputStream fout =context.openFileOutput(fileName,Context.MODE_PRIVATE);       byte [] bytes = fileContent.getBytes();       fout.write(bytes);       fout.close();     }       catch(Exception e){       e.printStackTrace();      }  }/** *   *@Title:ReadFileTxt *@param fileName *@return  *@throws IOException *@Description: 读txt文档,返回读出来的数 */public String ReadFileTxt(String fileName) throws IOException{     String res="";     try{            FileInputStream fin = context.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;      }

}

0 0