0

I have a piece of code that writes to a file using a DataOutputStream wrapped around a FileOutputStream, and writes to a string using a DataOutputStream wrapped around a ByteArrayOutputStream, both using the writeDouble() method.

I then try to read from the file and compare what is read from the file, to the string,(BufferedReader wrapped around a StringReader wrapped around b(ByteArrayOutputStream).toString(), and BufferedReader wrapped around a FileReader) and get the same result.

Even though

System.out.println(StrRead1.toString()) 

and

System.out.println(StrRead2.toString()) 

print the same thing in the terminal, when I compare the two using

(StrRead1.toString().equals(StrRead2.toString()))

they are never equal.(Str1 and Str2 being StringBuilders)

Can somebody give me a hand? Thanks.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • they might look visually the same, but one might have trailing white space, a line feed etc. – Uku Loskit Nov 17 '13 at 19:39
  • it could be trailing spaces. Use StrRead1.toString().trim().equals(StrRead2.toString().trim()); – ug_ Nov 17 '13 at 19:39
  • Try `System.out.println("[" + StrRead1.toString() + "]");` (and the same for 2). This is a good way to identify most (but not all) of the characters that may cause this issue. – nhgrif Nov 17 '13 at 19:41
  • 1
    It could be easier to spot the problem if you put more of your code in the question. – Robin Green Nov 17 '13 at 19:42
  • Why are you creating `String`s instead of using `FileInputStream` and `ByteArrayInputStream` and comparing byte for byte? – Holger Nov 17 '13 at 20:09

1 Answers1

0

The result of writeDouble() is binary. You have no business trying to turn the result into a String, or read that data with a Reader. Use an InputStream and compare the bytes. Or use a DataInputStream and compare the result of readDouble() in each case.

But I really have no idea why you're doing this. writeDouble() is writeDouble(). It does the same thing, regardless of what output stream it's connected to.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Thanks everybody. Must be rusty, because now that I've taken a good look, it shouldn't have been that hard. Just used a readDouble() to read in from the file and compare the result to a generated binary string, like above. – user3002384 Nov 17 '13 at 21:10