分享做过的java 生成 binary文件的例子

这篇博客展示了如何使用Java进行二进制文件的读写操作。通过`DataRecord`类,博主详细地解释了如何从固定格式的txt文件读取数据,将数据转换为二进制并存储到.bin文件中。此外,还提到了二进制文件的读取和二分查找在读取符合条件的数据集方面的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

废话少说,先上代码。


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;




class DataRecord {
public static final int RECORD_LENGTH = 131; 
private final int NAME_LENGTH = 22; // the maximum length allowed
private final int CODE_LENGTH = 7; // the maximum length allowed


private String code;


private String name;
private double double1;
private int int1;
private double double2;
private double double3;
private double double4;
private double double5;
private double double6;
private double double7;


public String getCode() {
return code;
}


public void setCode(String code) {
this.code = code;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public double getDouble1() {
return double1;
}


public void setDouble1(double double1) {
this.double1 = double1;
}


public int getInt1() {
return int1;
}


public void setInt1(int int1) {
this.int1 = int1;
}


public double getDouble2() {
return double2;
}


public void setDouble2(double double2) {
this.double2 = double2;
}


public double getDouble3() {
return double3;
}


public void setDouble3(double double3) {
this.double3 = double3;
}


public double getDouble4() {
return double4;
}


public void setDouble4(double double4) {
this.double4 = double4;
}


public double getDouble5() {
return double5;
}


public void setDouble5(double double5) {
this.double5 = double5;
}


public double getDouble6() {
return double6;
}


public void setDouble6(double double6) {
this.double6 = double6;
}


public double getDouble7() {
return double7;
}


public void setDouble7(double double7) {
this.double7 = double7;
}


@Override
public String toString() {
return "DataRecord [code=" + code + ", name=" + name + ", double1="
+ double1 + ", int1=" + int1 + ", double2=" + double2
+ ", double3=" + double3 + ", double4=" + double4
+ ", double5=" + double5 + ", double6=" + double6
+ ", double7=" + double7 + "]";
}
  //将数据以二进制形式存放到文件中
public void dumpObject(RandomAccessFile stream) {
StringBuffer str = new StringBuffer(name); // paddable county name
StringBuffer c = new StringBuffer(code);
try {
c.setLength(CODE_LENGTH);
stream.writeBytes(c.toString());

str.setLength(NAME_LENGTH);
stream.writeBytes(str.toString());

stream.writeDouble(double1);
stream.writeInt(int1);
stream.writeDouble(double2);
stream.writeDouble(double3);
stream.writeDouble(double4);
stream.writeDouble(double5);
stream.writeDouble(double6);
stream.writeDouble(double7);


} catch (IOException e) {
System.out.println("I/O ERROR: Couldn't write to the file;\n\t"
+ "perhaps the file system is full?");
System.exit(-1);
}
}
    //从二进制文件中读取记录
public void fetchObject(RandomAccessFile stream) {
byte[] ctyName = new byte[NAME_LENGTH]; // file -> byte[] -> String
byte[] cd = new byte[CODE_LENGTH];
try {
stream.readFully(cd);
code = new String(cd);

stream.readFully(ctyName);
name = new String(ctyName);
double1 = stream.readDouble();
int1 = stream.readInt();
double2 = stream.readDouble();
double3 = stream.readDouble();
double4 = stream.readDouble();
double5 = stream.readDouble();
double6 = stream.readDouble();
double7 = stream.readDouble();
} catch (IOException e) {
System.out.println("I/O ERROR: Couldn't read from the file;\n\t"
+ "is the file accessible?");
//System.exit(-1);
}
}
}


public class Prog1p1 {
public static void main(String[] args) throws IOException {
File fileRef; // used to create the file
RandomAccessFile dataStream = null; // specializes the file I/O
List<DataRecord> recs = new ArrayList<DataRecord>(); 



System.out.print("Please input you file name:");
BufferedReader str = new BufferedReader(
new InputStreamReader(System.in));
String fileName = str.readLine();
        System.out.println(fileName);
String newFileName = "";
// get the file name without it's extension

/**

* 处理文件名,保证获得的binary文件是原文件名+bin

* */
int pos1 = fileName.lastIndexOf("/");
int pos2 = fileName.lastIndexOf(".");


if (pos2 > 0) {
if (pos1 < 0)
pos1 = 0;
newFileName = fileName.substring(pos1, pos2);
}


recs = new Prog1p1().getDataRecords(fileName);
DataRecordComparator drc = new DataRecordComparator();
//把得到的list先排序
Collections.sort(recs, drc);


fileRef = new File(newFileName + ".bin");


try {
dataStream = new RandomAccessFile(fileRef, "rw");
} catch (IOException e) {
e.printStackTrace();
System.out.println("I/O ERROR: Something went wrong with the "
+ "creation of the RandomAccessFile object.");
System.exit(-1);
}
       //将list中的数据转换成binary,并存放到bin文件中
for (DataRecord rec : recs) {
System.out.println(rec.getCode());
rec.dumpObject(dataStream);
}


try {
dataStream.seek(0);
} catch (IOException e) {
System.out.println("I/O ERROR: Seems we can't reset the file "
+ "pointer to the start of the file.");
System.exit(-1);
}


   try {
            dataStream.close();
        } catch (IOException e) {
            System.out.println("I/O ERROR: Seems we can't reset the file "
                             + "pointer to the start of the file.");
            System.exit(-1);
        }


                


}
   //从txt文件读取数据存放到list中
private List<DataRecord> getDataRecords(String fileName) throws IOException {


FileReader fr = null;
BufferedReader buf = null;


List<DataRecord> recs = new ArrayList<DataRecord>();
try {


fr = new FileReader(fileName);
buf = new BufferedReader(fr);
String s = buf.readLine();
while (s != null) {


DataRecord rec = new DataRecord();
String[] sArr = s.split("\\^");
for (int i = 0; i < sArr.length; i++) {


}
    
rec.setCode(sArr[0].substring(1,sArr[0].length()-1).trim() );
rec.setName(sArr[1].substring(1,sArr[1].length()-1).trim() );
System.out.println(sArr[1]);
if(sArr[3].length()!=0)
rec.setInt1(Integer.parseInt(sArr[3]));
if(sArr[2].length()!=0)
rec.setDouble1(Double.parseDouble(sArr[2]));
if(sArr[4].length()!=0)
rec.setDouble2(Double.parseDouble(sArr[4]));
if(sArr[5].length()!=0)
rec.setDouble3(Double.parseDouble(sArr[5]));
if(sArr[6].length()!=0)
rec.setDouble4(Double.parseDouble(sArr[6]));
if(sArr[7].length()!=0)
rec.setDouble5(Double.parseDouble(sArr[7]));
if(sArr[8].length()!=0)
rec.setDouble6(Double.parseDouble(sArr[8]));

if(sArr[9].length()!=0) {
rec.setDouble7(Double.parseDouble(sArr[9]));
}

recs.add(rec);


s = buf.readLine();
}


} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
buf.close();
fr.close();


}


return recs;


}


}
//重写比较器
class DataRecordComparator implements Comparator<DataRecord> {
@Override
public int compare(DataRecord o1, DataRecord o2) {
if (o1.getInt1() > o2.getInt1())
return 1;
else if (o1.getInt1() == o2.getInt1()) {
if (o1.getInt1() > o2.getInt1())
return 1;
else if (o1.getInt1() == o2.getInt1())
return 0;
else
return -1;
} else
return -1;
}


}



大概就是从一个固定格式的txt文件读取出数据之后,然后将这些数据转换成二进制(非0,1那种),然后存到二进制文件中,后续还有二进制文件的而读取以及使用二分查找从二进制文件中读取符合条件的list集合的例子,欢迎围观!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值