1
1
134-png2021-08-29 18:04:30
Java
134-png, 2021-08-29 18:04:30

Why methods or code don't work properly?

As I understood from explanations from other sources about the mark and reset methods, my code should output: 1 4 2 6 2 6 3 -1. Instead, it outputs: 1 4 2 6 2 6 2 6 2 6... Please explain what is wrong.

ByteArrayInputStream dime = new ByteArrayInputStream(new byte[]{
            1, 4, 2, 6, 3
        });
        
        
        for(int i = 0; i != -1;){
            
            i = dime.read();
            
            if(i == 4) dime.mark(6);
            
            else if(i == 6) dime.reset();
            
            System.out.print(i + " ");
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-08-29
@134-png

It's not clear why you decided that. Most likely, you think that by calling reset, you "remove" the mark from the position. But this is not the case, this is not in the reset contract .

If such an IOException is not thrown, then the stream is reset to a state such that all the bytes read since the most recent call to mark (or since the start of the file, if mark has not been called) will be resupplied to subsequent callers of the read method

Therefore, every time you reset the stream to the marked position, and everything goes in cycles.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question