Android读取内存中的文件返回一个byte数组

来源:互联网 发布:金蝶软件 编辑:程序博客网 时间:2024/05/16 14:37

上一篇写到Android中byte数组生成文件并保存到手机

那么接下来我们学习一下Android读取内存文件返回byte数组

String PATH_BASE = Environment.getExternalStorageDirectory().getAbsolutePath() + "/contec";File _file = new File(PATH_BASE, "PM10_CASE_DAtA.txt");byte[] readFile = readFile(_file);private byte[] readFile(File file) {        // 需要读取的文件,参数是文件的路径名加文件名        if (file.isFile()) {            // 以字节流方法读取文件            FileInputStream fis = null;            try {                fis = new FileInputStream(file);                // 设置一个,每次 装载信息的容器                byte[] buffer = new byte[1024];                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();                // 开始读取数据                int len = 0;// 每次读取到的数据的长度                while ((len = fis.read(buffer)) != -1) {// len值为-1时,表示没有数据了                    // append方法往sb对象里面添加数据                    outputStream.write(buffer, 0, len);                }                // 输出字符串                return outputStream.toByteArray();            } catch (IOException e) {                e.printStackTrace();            }        } else {            //System.out.println("文件不存在!");        }        return null;    }