开发者

InputStream read(byte[] b, int off, int len) - Drop the rest of the file?

This is an extension of a question I asked on here this morning so please don't disregard if you think you've seen this code before :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");
}

Hi there, after hours of struggling to get this code to how it is, I've almost finished the particular component that I am working on. The program takes in a specified file and is supposed to convert the first 10 bytes of that file into Hex. Once it has acquired the first 10 bytes of that file, it should stop and move onto the next sp开发者_StackOverflowecified file. Currently, it takes the entirety of the file and divides it into multiple 10 byte 'chunks' which it then prints out. In other words, it isn't stopping after the first 10 bytes which I thought read(byte[] b, int off, int len) did

Example output:

74656173676173677361

67616773617367616773

61676173617367616773

but instead it should produce

74656173676173677361

Any advice would be hugely appreciated it and I really do mean that :)


What about dropping the while-loop? As I already told you in your first question, the following is the way to go in case you're sure there are always at least 10 bytes:

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

Otherwise go for something like this:

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;
}


You have a while loop inside your outer for loop ( while((read = in.read(b, 0, 10)) != -1) ) that is cycling through all of the bytes in the whole file.

Try a simple for(int i = 0; i < 10; i++) that reads a single byte from in, and converts those to hex.

And don't forget to close your files and input streams in a finally{} clause!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜