二进制 文件 读入_JavaNote 二进制文件读写

6e534ce49a2ed4f9175e60dc1477cf7e.png

二进制文件

  • 狭义上,采用字节编码,非字符编码的文件
  • 广义上,一切文件都是二进制文件
  • 用记事本等无法打开/阅读

二进制文件读写

  • 输出数据到文件中
  • 从文件中读取数据

写文件

  • 先创建文件,写入数据,关闭文件
  • FileOutputStream
  • BufferedOutputStream
  • DataOutPutStream
    • flush 刷新缓存
    • write/writeBoolean/writeByte/writeDouble/writeInt/WriteUTF/···
    • try-resouce语句,自动关闭资源
    • 关闭最外层的数据流,将会把其上所有的数据流关闭
import java.io.*;
public class BinFileWrite{
  public static void main(String[] args) throws Exception{
	writeFile();
    System.out.println("done.");
  }
  
  public static void writeFile() {
	  FileOutputStream fos = null;
	  DataOutputStream dos = null;
	  BufferedOutputStream bos = null;
		try {
			fos = new FileOutputStream("c:/temp/def.dat"); // 节点类
			bos = new BufferedOutputStream(fos); //装饰类
			dos = new DataOutputStream(bos); // 装饰类		
			
			dos.writeUTF("a");
			dos.writeInt(20);
			dos.writeInt(180);
			dos.writeUTF("b");
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {//关闭打开的文件资源
			try {
				dos.close(); // 关闭最后一个类,会将所有的底层流都关闭
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
}

读文件

  • 先打开文件,读入数据,关闭文件
  • FileInputStream
  • BufferedInputStream
  • DataInputStream
    • read;readBoolean;readDouble;readFloat;readInt;readUTF
  • try-resource语句,自动关闭资源
  • 关闭最外层数据流,将会把其上所有的数据流关闭
import java.io.*;
public class BinFileRead{
  public static void main(String[] args) throws Exception{
	  readFile();
  }
  public static void readFile() {
		//try-resource 
		try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream("c:/temp/def.dat")))) {
			String a, b;
		    int c, d;
		    a=dis.readUTF();
		    c=dis.readInt();
		    d=dis.readInt();
		    b=dis.readUTF();
		    System.out.println("a: "+a);
		    System.out.println("c: "+c);
		    System.out.println("d: "+d);
		    System.out.println("b: "+b);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}

输出结果:

a: a
c: 20
d: 180
b: b

f95ce24482fee0903cb2078a8aa06bb0.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值