从Java中的FileInputStream读取字节

从FileInputStream读取字节

以下示例显示了如何从Java中的FileInputStream读取字节。

import java.io.File;
import java.io.FileInputStream;
public class fileInputStream {
    public static void main(String[] args) {
        byte[] data = new byte[1024];  //分配1024个字节的内存
        //请注意如何在Java中声明数组
        int readBytes;
        try {
            File file = new File("testfile");
            file.createNewFile();
            FileInputStream in = new FileInputStream(file);
 
            while ((readBytes = in.read(data)) != -1) {
             //读取(字节[] B)
             //读取从输入流的字节,并将它们存储一些数到缓冲区数组b。
                System.out.println("read " + readBytes + " bytes, and placed them into temp array named data");
                System.out.println("data :" + data[123]);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

如果放置一些数据,它将给出以下输出:

run:
read 1024 bytes, and placed them into temp array named data
read 1024 bytes, and placed them into temp array named data
read 1024 bytes, and placed them into temp array named data
read 1024 bytes, and placed them into temp array named data
read 1024 bytes, and placed them into temp array named data
read 1024 bytes, and placed them into temp array named data
read 952 bytes, and placed them into temp array named data
BUILD SUCCESSFUL (total time: 2 seconds) 

在这里插入图片描述

发布了0 篇原创文章 · 获赞 0 · 访问量 103

猜你喜欢

转载自blog.csdn.net/qq_41806546/article/details/105135439