java - Why is this loop becoming infinite when using String.valueOf or Float.toString? -
i reading in bytes file using fileinputstream. code (in correct form) follows:
string s = ""; try { file file = new file(...); fileinputstream file_input = new fileinputstream(file); datainputstream data_in = new datainputstream(file_input ); while (true) { try { (int index = 0; index < 4; index++) { bytearray[index] = data_in.readbyte(); } } catch (eofexception eof) { break; } float f = readfloatlittleendian(bytearray); // transforms 4 bytes float //s += float.tostring(f); <- here's problem } data_in.close(); } catch (ioexception e) { system.err.println(e.tostring()); } } system.out.print(s); if run code is, loop finishes when reading of file , transforming each set of 4 bytes float.
however, if uncomment line, file never finishes, , seems loop through file on , over. also, printing f (without using float.tostring or string.valueof) not turn infinite loop.
the loop not become infinite - grossly inefficient. problem += on java.lang.string produces new immutable object, discarding 1 held before. each time makes copy, making process o(n2) in terms of number of entries in file.
the fix straightforward - replace string s stringbuilder s, , use append in place of +=.
stringbuilder s = new stringbuilder(); try { file file = new file(...); fileinputstream file_input = new fileinputstream(file); datainputstream data_in = new datainputstream(file_input ); while (true) { try { (int index = 0; index < 4; index++) { bytearray[index] = data_in.readbyte(); } } catch (eofexception eof) { break; } float f = readfloatlittleendian(bytearray); // transforms 4 bytes float s.append(f); } data_in.close(); } catch (ioexception e) { system.err.println(e.tostring()); } system.out.print(s);
Comments
Post a Comment