以下示例显示了如何从Java中的FileInputStream读取字节。
import java.io.File;import java.io.FileInputStream;public class fileInputStream {
public static void main(String[] args) {
byte[] data = new byte[1024]; //allocates memory for 1024 bytes
//be careful about how to declare an array in Java
int readBytes;
try {
File file = new File("testfile");
file.createNewFile();
FileInputStream in = new FileInputStream(file);
while ((readBytes = in.read(data)) != -1) {
//read(byte[] b)
//Reads some number of bytes from the input stream and stores them into the buffer array 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)
最后,开发这么多年我也总结了一套学习Java的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。