1 import java.io.DataInputStream; 2 import java.io.DataOutputStream; 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 8 /* @comany 阿斯达克(深圳)信息技术有限公司 9 * @author steven.wu 10 * @since 2009.8.11 11 * @description read and write stream for binary file。 12 */ 13 public class BinaryReadWrite { 14 private DataInputStream dis=null; 15 private DataOutputStream dos=null; 16 private String s_FilePath="d:/bin.dat"; 17 private byte[] m_datapadding = { 0x00 }; //填充空白,以补足字节位数. 18 19 public BinaryReadWrite() { 20 // TODO Auto-generated constructor stub 21 init(); 22 } 23 private void init(){ 24 try{ 25 if(!new File(s_FilePath).exists()){ 26 new File(s_FilePath).createNewFile(); 27 } 28 dis=new DataInputStream(new FileInputStream(new File(s_FilePath))); 29 dos=new DataOutputStream(new FileOutputStream(new File(s_FilePath),true));////如果文件存在,这追加数据true 30 }catch(Exception e){ 31 e.printStackTrace(); 32 } 33 } 34 public void writeBinaryStream(){ 35 try{ 36 if(dos!=null){ 37 for(int i=0;i<2;i++){ 38 //write boolean value. 39 dos.writeBoolean(true); 40 //write a char value. 41 char c=‘a‘; 42 dos.writeChar((int)c); 43 Double d=12.567d; 44 dos.writeDouble(d); 45 Float f=56.782f; 46 dos.writeFloat(f); 47 int k=105; 48 dos.writeInt(k); 49 long l=98765l; 50 dos.writeLong(l); 51 short st=12; 52 dos.writeShort(st); 53 String cs="Java读写二进制文件"; 54 String cs1="二进制文件"; 55 if(i==0){ 56 dos.writeUTF(cs); 57 }else{ 58 dos.writeUTF(cs1); 59 } 60 dos.write(m_datapadding); 61 } 62 dos.flush(); 63 dos.close(); 64 } 65 }catch(Exception e){ 66 e.printStackTrace(); 67 } 68 } 69 public void readBinaryStream(){ 70 try{ 71 if(dis!=null){ 72 while(dis.available()>0){ 73 System.out.println(dis.available()); 74 System.out.println(dis.readBoolean()); 75 char c=(char)dis.readChar(); 76 System.out.println(c); 77 System.out.println(dis.readDouble()); 78 System.out.println(dis.readFloat()); 79 System.out.println(dis.readInt()); 80 System.out.println(dis.readLong()); 81 System.out.println(dis.readShort()); 82 System.out.println(dis.readUTF()); 83 System.out.println(dis.read(m_datapadding)); 84 } 85 } 86 }catch(Exception e){ 87 e.printStackTrace(); 88 } 89 } 90 public static void main(String[] args) throws IOException { 91 BinaryReadWrite bin=new BinaryReadWrite(); 92 bin.writeBinaryStream(); 93 bin.readBinaryStream(); 94 } 95 }
代码摘自:https://blog.csdn.net/steven2006/article/details/4434621
这里只是保存一下,方便查看。
原文:https://www.cnblogs.com/tomorrow-is-better/p/10809949.html