Hi all,
I have an array of long that I would like to write into a .txt file that I can later open in gedit (one number per line). I get those values by using a subtraction of two instances of System.currentTimeMillis().
I use the following code:
BufferedWriter out = new BufferedWriter(new FileWriter("latency.txt"));
for (int i = 0; i < USER_LIMIT; ++i) {
out.write(latency[i] + "\n");
}
out.close();
When looking at the file, I do see:
0
1
1
0
I believe the string concatenation converted the long into an integer. If I use the DataOutputStream, then I cannot read it back with gedit or any notepad/text editor, it just looks like g开发者_如何学Goarbage (I believe it's writing bytes).
Would anyone please let me know how I can fix my problem please?
Thank you very much!
There is nothing wrong with your code. What you think is in latency
... isn't.
public static void main(String[] args) throws IOException
{
long[] latency = { 123456789000L, 234567890000L, 345678901000L };
BufferedWriter out = new BufferedWriter(new FileWriter("latency.txt"));
for (int i = 0; i < 3; ++i) {
out.write(latency[i] + "\n");
}
out.close();
}
produces:
$ more latency.txt
123456789000
234567890000
345678901000
When you're having a problem with code like this, it's often beneficial to write a small test case to narrow down the problem.
Cast to a Long and use toString:
out.write(((Long)latency[i]).toString() + "\n");
Or just use the static toString:
out.write(Long.toString(latency[i]) + "\n");
When you use DataOutputStream to write a long it is using a different encoding of your data than gedit understands.
One of the most common encodings used for text files is ASCII. With this each byte represents a character in a table. This table has 128 characters. When you write a string to a file using Java the way you're doing it this is what is happening and gedit understands that encoding. If you convert a long to a string the maximum size a long can be would look like: 9223372036854775807. That would take up 19 bytes.
A long in Java is 64 bits or 8 bytes. When you use DataOutputStream a long gets written to the file as 8 bytes. A text editor like gedit does not understand this encoding.
What further complicates things is encodings such as UTF-8.
You don't need to append the newline to the number, so you can break them apart and avoid this problem. Try this:
for ( int i = 0; i < USER_LIMIT; ++i ) {
out.write( String.valueOf(latency[i]) ); // Or Long.toString(long)
out.write( '\n' ); // Or simply out.newLine()
}
精彩评论