Joel DeWitt
Joel DeWitt

Reputation: 1306

Use of writeDouble produces nonsense

This question is essentially an extension of the discussion found here. My goal is to write two formatted columns of arrayed x and y data to file (type double). My current attempt to accomplish this is as follows:

try {
  FileOutputStream fos = new FileOutputStream("angle.txt");
  DataOutputStream dos = new DataOutputStream(fos);
  for (i = 0; i < i_max-1; i = i + 1) {
    dos.writeDouble(theta[i]);
  }
  dos.close();
} catch (IOException error) {
  System.out.println("IOException: " + error);
}

This code is derived from the example found here (DataOutputStream). Having a limited grasp of Java, I expected this to work for one column only; instead it produced this:

?¹™™™™™š?¹™™™™™š?¹™™™™™š?¹™™™™™š?¹™™™™™š?¹™™™™™š?¹™™™™™š?¹™...

I don't understand what I'm doing wrong. Any insights you can offer will be a great help.

My next question would be: How do I format not one but two columns of type double, formatted something like ("%1$16.6f, %2$16.6f", time[i], theta[i]). Right now I'm following this discussion. However, the compiler dislikes this approach with the use of writeDouble.

Your help and patience will be most appreciated.

Upvotes: 0

Views: 47

Answers (2)

Joel DeWitt
Joel DeWitt

Reputation: 1306

Solution:

try {
  PrintWriter writer = new PrintWriter("angle.txt", "UTF-8");
  for (i = 1; i < i_max; i = i + 1) {
    writer.printf("%1$16.6f%2$16.6f%n", time[i], theta[i]);
  }
  writer.close();
} catch (IOException ioe) {
  System.out.println(ioe);
}

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692071

Streams are used to write binary data. To write textual data, you use Writers. See the Java IO tutorial: http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html

Upvotes: 4

Related Questions