因此,我使用字节流将 0 到 100000 之间的一系列整数值写入文本文件,以确保它们以正确的格式存储,我正在尝试使用输入流查看数字。我尝试了几种方法,但是每次我打印出的数字不正确时,任何人都可以看到我哪里出错了,或者对读取输入流的替代方法有任何想法:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;
public class Question1ByteStream {
public static void main(String[] args) throws IOException {
//************************************************************
//WRITING TO THE FILE
FileOutputStream out = null;
try {
out = new FileOutputStream("ByteOutStream.txt");
for(int i = 0; i < 10000; i ++){
Integer randomNumber = randInt(0, 100000);
byte[] bytes = ByteBuffer.allocate(4).putInt(randomNumber).array();
out.write(bytes);
}
}finally{
if (out != null) {
out.close();
}
}
//***********************************************************
//READING BACK FROM THE FILE
FileInputStream in = null;
try {
in = new FileInputStream("ByteOutStream.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
}
}
//***************************************************************
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}