集册 Java实例教程 从文件获取字节

从文件获取字节

欢马劈雪     最近更新时间:2020-01-02 10:19:05

425
从文件获取字节
// 来自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m


//package com.nowjava;


import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;


public class Main {

    public static void main(String[] argv) throws Exception {

        File file = new File("Main.java");

        System.out.println(java.util.Arrays

                .toString(getBytesFromFile(file)));

    }


    public static byte[] getBytesFromFile(File file) throws IOException {

        InputStream is = new FileInputStream(file);


        long length = file.length();
/* 来 自 nowjava - 时代Java*/

        if (length > Integer.MAX_VALUE) {

            // File is too large

        }


        byte[] bytes = new byte[(int) length];


        int offset = 0;

        int numRead = 0;

        while (offset < bytes.length

                && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {

            offset += numRead;

        }


        
展开阅读全文