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

从文件获取字节

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

456
从文件获取字节
/*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();


        if (length > Integer.MAX_VALUE) {

            // File is too large/*时 代 J a v a 公 众 号 - nowjava.com 提供*/

        }


        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;

        }


        
展开阅读全文