用Java读取文件的前10个字节

for (String name : filenames) { FileInputStream in = new FileInputStream(input.readUTF()); int byteCounter = 0; int rowCounter = 0; long bufferCounter = 0; byte[] b = new byte[8]; int read; //in.skip(10); //while((read = in.read()) != -1){ while((read = in.read(b, 0, 10)) != -1){ byteCounter ++; if (byteCounter != 1000){ if (rowCounter == 16){ System.out.println("\n"); rowCounter = 0; } System.out.print(Integer.toHexString(read) + "\t"); bufferCounter ++; rowCounter ++; }else{ byteCounter = 0; try{ Thread.sleep(200); }catch(InterruptedException e) { } } } System.out.println("\n"+"================"+"\n"); } 

嗨,我希望有人可以帮助我解决我一直遇到的问题。 我正在尝试让我的程序读取指定文件的前10个字节。 我可以让它与skip()一起工作,但显然这与我想要的相反(它取消了前10个)我看起来一无所获,如果你可以帮助我,那就是大。 您可能已经看到我已经尝试将读取(b,off,len)输入到代码中但是这只会产生随机字符作为输出而不是我想要的实际hex字符74 65 71等(编辑:这些随机字符似乎是读取的字节数的hex代码。因此,对于一个包含23个hex字符的文本文件,它会生成一个3(或换句话说:10,10,3 = 23)

问题出在这里

 System.out.print(Integer.toHexString(read) + "\t"); 

read包含从流中有效读取的字节数。 Teh字节在数组b

顺便说一句:你的数组大小为8.如果你想读取10个字节,你应该将它增加到10!

 byte[] b = new byte[10]; new DataInputStream(new FileInputStream(input.readUTF())).readFully(b); 

这是最简单的方法,但是如果可用的字节少于10个,则抛出它。 如果您不想要它,请使用循环。 不知怎的,我不知道你在做什么,它看起来不像是读取前10个字节: if (byteCounter != 1000)