如何将某些条件从二进制文件写入文本文件

How to write certain criteria into a text file from a binary file

我开发了一种方法,可以从 .data 文件中提取所有数据并将它们写入文本文件

myTextFile = new PrintWriter(
                    new BufferedOutputStream(new FileOutputStream("file.txt")));
            input = new DataInputStream(new FileInputStream(new File("file.data")));



  //This loop will take all info found in file.data but what if I want only where country is USA for exemple 
            while (input.available() > 0) {

                countryNumber = input.readInt();
                population = input.readInt();
                region = input.readUTF();
                State = input.readUTF();
                loan = input.readInt();
                categorie = (input.readChar());
                adresse = (input.readUTF());
                descrpt = input.readUTF();
            //Now I  print all info from file.data to file.txt
       myTextFile.println(region.toString() + " " + population.toString() + " " + region + " " + State + " " + categorie + " " + loan + " " + adresse);

            }
 myTextFile.close();
            input.close();

如您所见,我创建了一个循环 While(imput.available()>0,它将获取 file.data 中找到的所有数据并将所有内容写入文本文件

但是如果我只想在文本文件中写入 region = NewYork 怎么办?并在文本文件中写下纽约的人口、州等……?

他们有什么办法可以限制标准吗?

非常感谢,

低音

做这种事情的最好方法是按记录为每条记录分配固定数量的字节,我指的是元组 countryNumber、population、region、State、loan、categorie、addresse 和 descrpt。然后你把你的区域的值作为你记录的第一个值这样你就可以读取区域,检查它是否是预期的区域,如果是这样你可以停止读取文件否则你直接转到下一条记录等等。

这种方法允许您只读取文件的子部分,而不是读取更优化的所有内容。

在编写之前,您可以添加一个 if 语句来检查是否 region.equals("NewYork")。 那将是:

if(region.equals("NewYork")) myTextFile.println(region.toString() + " " + population.toString() + " " + region + " " + State + " " + categorie + " " + loan + " " + adresse);