![](/img/trans.png)
[英]Is the method read(byte b[], int off, int len) in InputStream same as the method read(byte b[], int off, int len) in FileInputStream?
[英]InputStream read(byte[] b, int off, int len) - Drop the rest of the file?
这是我今天上午在这里提出的问题的扩展,因此,如果您认为自己在:D之前已经看过此代码,请不要忽略
for (String name : filenames) {
FileInputStream in = new FileInputStream(input.readUTF());
int byteCounter = 0;
int rowCounter = 0;
long bufferCounter = 0;
byte[] b = new byte[10];
int read;
//in.skip(10);
//while((read = in.read()) != -1){
while((read = in.read(b, 0, 10)) != -1){
byteCounter ++;
if (byteCounter != 1000){
if (rowCounter == 1){
System.out.println("\n");
rowCounter = 0;
}
System.out.print(org.apache.commons.codec.binary.Hex.encodeHexString(b));
bufferCounter ++;
rowCounter ++;
}else{
byteCounter = 0;
try{
Thread.sleep(200);
}catch(InterruptedException e) {
}
}
}
System.out.println("\n"+"================"+"\n");
}
嗨,在那里,经过数小时的努力来使这段代码变得真实,我几乎已经完成了我正在研究的特定组件。 该程序接收一个指定的文件,并且应该将该文件的前10个字节转换为Hex。 一旦获取了该文件的前10个字节,它应停止并移至下一个指定的文件。 当前,它将获取整个文件并将其分成多个10字节的“块”,然后将其打印出来。 换句话说,它并没有在我认为read(byte [] b,int off,int len)完成的前10个字节之后停止
输出示例:
74656173676173677361
67616773617367616773
61676173617367616773
但是它应该产生
74656173676173677361
任何建议将不胜感激,我确实的意思是:)
如何删除while循环? 正如我在第一个问题中已经告诉您的那样,如果您确定始终至少有10个字节,可以采用以下方法:
byte[] b = new byte[10];
new DataInputStream(new FileInputStream(input.readUTF())).readFully(b);
否则,请执行以下操作:
byte[] b = new byte[10];
int count = 0;
while (count < b.length) {
int n = in.read(b, count, b.length-count);
if (n==-1) break;
count += n;
}
您的外部for循环内部有一个while循环(while((read = in.read(b,0,10))!= -1))循环遍历整个文件中的所有字节。
尝试一个简单的for(int i = 0; i <10; i ++),它从in读取一个字节,并将其转换为十六进制。
并且不要忘了在finally {}子句中关闭文件和输入流!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.