G
G
gleendo2017-01-15 20:59:37
Java
gleendo, 2017-01-15 20:59:37

How to check the output stream filter?

There was a task to write an output stream filter so that it filters out bytes equal to 0.
It seems like I wrote it, and I'm almost sure that everything should work. But now I don't know how to check if the code works. What values ​​can be copied to another file that will have bytes equal to 0 to see that they are not copied? Or did I mess something up. In general, how to check the written code?

import java.io.*;
import java.util.Arrays;

class ZeroFilter {
    static void filter(InputStream src, OutputStream dst, int buffSize) throws IOException {
        final int ZERO_STATE = 0;
        final int NUMBERS_STATE = 1;
        byte[] buff = new byte[buffSize];
        int count;

        while ((count = src.read(buff)) != -1) {
            int state = ZERO_STATE;
            int fromIndex = -1;

            for (int index = 0; index < count; index++) {
                byte elem = buff[index];

                switch (state) {
                    case ZERO_STATE:
                        if (elem == 0) {
                            state = ZERO_STATE;
                        } else {
                            fromIndex = index;
                            state = NUMBERS_STATE;
                        }

                        break;
                    case NUMBERS_STATE:
                        if (elem == 0) {
                            dst.write(Arrays.copyOfRange(buff, fromIndex, index));

                            state = ZERO_STATE;
                        } else {
                            state = NUMBERS_STATE;
                        }
                }
            }

            if (state == NUMBERS_STATE) {
                dst.write(Arrays.copyOfRange(buff, fromIndex, buff.length));
            }
        }

//        while (true) {
//            int value = src.read();
//
//            if (value > 0) {
//                dst.write(value);
//            } else if (value == -1) {
//                break;
//            }
//        }
    }
}

public class App {
    public static void main(String[] args) throws IOException {
        try (FileInputStream fis = new FileInputStream("c://infile.txt"); FileOutputStream fos = new FileOutputStream("c://outfile.txt")) {
            ZeroFilter.filter(fis, fos, 16);
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
aol-nnov, 2017-01-15
@aol-nnov

well, unit tests!
you make an input stream of zeros (ByteArrayInputStream, for example), you feed it to your beast. If the output is nothing, then something is working.
You make another thread pattern at the input and expect some kind of output. compared to expectation.
it is convenient to run tests, for example, through JUnit

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question