test

博客园 首页 新随笔 联系 订阅 管理

 文件转字节流

    /**
     *
     * <p>Title: getContent</p>
     * <p>Description:根据文件路径读取文件转出byte[] </p>
     * @param filePath文件路径
     * @return 字节数组
     * @throws IOException
     */
    public static byte[] getContent(String filePath) throws IOException {
        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            System.out.println("file too big...");
            return null;
        }
        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length
                && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        // 确保所有数据均被读取
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }
        fi.close();
        return buffer;
    }
    

 

字节流写文件

            String path = "files/" + filename;
            //将文件流写到本地文件
            InputStream inputStream = new ByteArrayInputStream(fileByte);
            OutputStream outputStream = new FileOutputStream(path);
            byte[] byts = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(byts)) != -1) {
                outputStream.write(byts, 0, len);
                outputStream.flush();
            }
            inputStream.close();
            outputStream.close();

 

posted on 2019-12-10 22:17  testgogogo  阅读(343)  评论(0编辑  收藏  举报