使用DataInputStream和DataOutputStream读写二进制文件.bin
使用PrintWriter写入文本文件请参考:https://blog.csdn.net/qq_43524683/article/details/99689599
使用Scanner和BufferedReader读取文本文件请参考:https://blog.csdn.net/qq_43524683/article/details/99646584
1. 主函数
public static void main(String[] args) {
Demo demo = new Demo();
demo.writeBinFiles(); //写入二进制文件
demo.readBinFiles(); //读出二进制文件
}
主函数中将这两种方法分别封装在两个方法中。
2. 使用DataOutputStream写入二进制文件
public void writeBinFiles(){
String fileNmae="F:\\IDEA_Codes\\Write&ReadBinFiles\\src\\integers.bin";
Scanner keyboard=new Scanner(System.in);
System.out.println("Creating a file of integers that you enter");
FileOutputStream fos=null;
DataOutputStream toFile=null; //DataOutputStream没有以文件名为参数的构造器,使用中间类FileOutputStream
//若文件不存在则创建,存在则覆写
//FileOutputStream fos=new FileOutputStream(fileNmae,true); //追加式写入
try{
fos=new FileOutputStream(fileNmae); //可以抛出FileNotFoundException异常
toFile=new DataOutputStream(fos);
System.out.println("Enter nonnegative integers,one per line,end with a negative number:");
int number=keyboard.nextInt();
while (number>=0){
toFile.writeInt(number); //写入整数 writeInt() 写入字符串writeString()
number=keyboard.nextInt();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) { //writeInt()可抛出此异常
e.printStackTrace();
} finally {
try{
if(toFile!=null)
toFile.close(); //关闭文件
}catch (IOException e) {
e.printStackTrace();
}
}
}
类DataOutputStream没有以文件名作为参数的构造器,因此这里使用中间类FilOutpStream,其构造函数使用一个文件名创建数据流,然后把这个数据流传递给DataOutputStream的构造函数。
若文件integers.bin文件不存在,则创建一个文件;若文件integer.bin已经存在,则语句清楚它的内容,以至文件重新变为空。
DataOutputStream同样也有其他的writeDouble、writeFloat、writeChar、writeUTF等方法。
为了将程序的输出添加到二进制文件中已有数据的后面,即将数据追加到文件中,则可如下所示打开文件:
FileOutputStream fos=new FileOutputStream(fileNmae,true); //追加式写入
3. 使用DataInputStream读出二进制文件
public void readBinFiles(){
String fileName="F:\\IDEA_Codes\\Write&ReadBinFiles\\src\\integers.bin";
DataInputStream fromFile=null;
try {
FileInputStream fis=new FileInputStream(fileName); //可以抛出FileNotFoundException异常
fromFile=new DataInputStream(fis);
System.out.println("Reading all the integers in the file "+fileName);
while (true){ //根据EOFException异常来中断循环的进行
int nextNumber=fromFile.readInt(); //与writeInt()相照应,可以抛出IOException异常
System.out.println(nextNumber);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (EOFException e){ //如果文件到达末尾,则抛出此异常
System.out.println("End of the file "+fileName+" reached.");
} catch (IOException e) {
e.printStackTrace();
}finally {
try{
if(fromFile!=null)
fromFile.close(); //可以抛出IOException异常
} catch (IOException e) {
e.printStackTrace();
}
}
}
二进制文件并不是人可读的数据,在读取二进制数据中,与上对应,这里使用DataInputStream的readInt()方法。如果发生错误,则抛出一个IOException异常,如果到达了文件末尾,则抛出EOFException异常。
于是在下面的while语句中根据EOFException异常来中断循环的进行。
结果如下: