How should I really go about implementing the following? I will have to handle a byte array that will contain text on several lines. The average size of the data is probably going to be around 10 kilobytes of data.
After unspecified amount of lines there will be a line starting with special token ("FIRSTSTRING"). Later somewhere on the same file there will be an other line also starting with a special token ("SECONDSTRING"). If both the first and second lines are defined in the byte array the second line should be copied in place of the first line. After that the resultant byte array should be returned.
Below is my first attempt. I did not refactor it to reduce complexity yet. I am concerned about reliablity and also very much about performance. It seems there are too many ways going around this and I lack experience required for judgement. I would really appreciate some good input on this.
private byte[] handleHeader(final byte[] input) throws IOException {
// input
ByteArrayInputStream bais = new ByteArrayInputStream(input);
InputStreamReader isr = new InputStreamReader(bais);
BufferedReader brs = new BufferedReader (isr);
// output
ByteArrayOutputStream data = new ByteArrayOutputStream();
ByteArrayOutputStream after = new ByteArrayOutputStream();
String line=null;
String original=null;
String changeWith=null;
while ((line = brs.readLine())!=null) {
line+="\n";
if (line.startsWith("FIRSTSTRING")) {
original = line;
continue;
}
if (line.startsWith("SECONDSTRING")) {
changeWith = line;
continue;
}
if ("".equals(original)) {
data.write(line.getBytes());
} else {
after.write(line.getBytes());
}
}
if (changeWith!=null && original != null) {
changeWith+="\n";
data.write(changeWith.getBytes());
} else if (original != null){
data.write(original.getBytes());
}
after.writeTo(data);
return data.toByteArray();
}