android文件写入和读取

//读写文件函数调用
writeFileData(filename,datas);
String result=readFileData(filename); Toast.makeText(Main2Activity.this,result.getClass().toString(),Toast.LENGTH_SHORT).show();

下面是读写代码的实现:

//文件写入
    public void writeFileData(String filename, String content){
        try {
            FileOutputStream fos = this.openFileOutput(filename, MODE_PRIVATE);//获得FileOutputStream
            //将要写入的字符串转换为byte数组
            byte[]  bytes = content.getBytes();
            fos.write(bytes);//将byte数组写入文件
            fos.close();//关闭文件输出流

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //文件读取
    public String readFileData(String fileName){
        String result="";
        try{
            FileInputStream fis = openFileInput(fileName);
            //获取文件长度
            int lenght = fis.available();
            byte[] buffer = new byte[lenght];
            fis.read(buffer);
            //将byte数组转换成指定格式的字符串
            result = new String(buffer, "UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  result;
    }

猜你喜欢

转载自www.cnblogs.com/gaoyukun/p/10151701.html