有没有人知道如何从一个文件中读取不同的二进制数?(如何区分这两种类型)
问题描述:
在这个程序员中,我发现前100个素数。数字是INT格式,它们的总数都是DOUBLE格式。我想读取该文件,我只为INT数字,但我不知道热的做它的双数。 下面是代码:有没有人知道如何从一个文件中读取不同的二进制数?(如何区分这两种类型)
package int1;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.channels.FileChannel;
public class int_upis {
public static void main(String[] args) {
File a = new File("C:\\Users\\Jovan\\Desktop\\Pisem.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(a);
} catch (Exception e) {
}
FileChannel ch = fos.getChannel();
ByteBuffer bff = ByteBuffer.allocate(100);
IntBuffer ibf = bff.asIntBuffer(); // Int type
DoubleBuffer db = bff.asDoubleBuffer(); // Double type
double p = 0;
for (int i = 1; i <= 100; i++) {
int t = 0;
for (int j = 1; j <= i; j++) {
if (i % j == 0) {
t = t + 1;
}
}
if (t < 3) {
p = p + 1; // number of Prime numbers
System.out.println(i);
ibf.put(i);
bff.position(4 * ibf.position());
bff.flip();
try {
ch.write(bff);
bff.clear();
ibf.clear();
} catch (IOException e) {
}
}
}
try {
db.put(p); //At the end of the txt-file i put double format of number (Number of Prime numbers)
bff.position(8*db.position());
bff.flip();
ch.write(bff);
System.out.println("File is writen with: " + ch.size());
ch.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
现在我试图读取该文件:
public class int_ispis {
public static void main(String[] args) throws IOException {
File a = new File("C:\\Users\\Jovan\\Desktop\\Pisem.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(a);
} catch (Exception e) {
}
FileChannel ch = fis.getChannel();
ByteBuffer bff = ByteBuffer.allocate(6 * 4);
这是素数放在一个6行阵列(低于此线)的一行:
int[] niz = new int[6];
System.out.println("Pre flipa: " + bff.position() + " " + bff.limit());
System.out.println("++++++++++++++++++++++++++++++++++++");
while (ch.read(bff) != -1) {
bff.flip();
System.out.println();
System.out.println("Posle flipa: " + bff.position() + " " + bff.limit());
IntBuffer ib = bff.asIntBuffer();
System.out.println("IB: " + ib.position() + " " + ib.limit());
int read = ib.remaining();
System.out.println(read);
的时候才来文件的末尾它把双号为整数,并写入错误的号码(如何分离整数形式的双号?)
ib.get(niz, 0, ib.remaining());
for (int i = 0; i < read; i++) {
System.out.print(niz[i] + " ");
}
System.out.println();
System.out.println("=================================");
ib.clear();
bff.clear();
}
}
}
答
二进制文件没有任何“分隔符”。
您需要知道的结构的文件内容并使用了这些知识。
在这个程序员中,我发现前100个素数。数字是INT格式,它们的总数都是DOUBLE格式。
这意味着只有一个long
在文件中的值,这是在最后8个字节。因此,您只需检查当前位置是否为fileLenght - 8
,然后将这些最后8个字节作为long
值读取。