Writing a long (primitive type) to a file in Java
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.
Jary
Updated on June 27, 2022Comments
-
Jary almost 2 years
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 garbage (I believe it's writing bytes).
Would anyone please let me know how I can fix my problem please?
Thank you very much!