首页 > 编程语言 > 详细

java 文件流的知识点

时间:2019-12-10 22:26:48      阅读:129      评论:0      收藏:0      [点我收藏+]

 文件转字节流

    /**
     *
     * <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();

 

java 文件流的知识点

原文:https://www.cnblogs.com/kkvt/p/12019571.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!