以下示例顯示了如何從Java中的FileInputStream讀取字節。
importjava.io.File;import java.io.FileInputStream;publicclass fileInputStream {
publicstaticvoidmain(String[] args) {
byte[] data = newbyte[1024]; //allocates memory for 1024 bytes
//be careful about how to declare an array in Java
intreadBytes;
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 952 bytes, and placed them into temp array named data
BUILD SUCCESSFUL (total time: 2 seconds)
最後,開發這麼多年我也總結了一套學習Java的資料與面試題,如果你在技術上面想提升自己的話,可以關注我,私信發送領取資料或者在評論區留下自己的聯繫方式,有時間記得幫我點下轉發讓跟多的人看到哦。