0

I am trying to store an arraylist of floating points to a file.
I tried using a DataOutputStream to write to the file and it works just fine except that the data is not written in human-readable format.
I know I must use print writer to write the data in text format, however it does not support writing floating points.

PrintWriter writer = new PrintWriter("filename.txt");
writer.write(naiveNearestPoints(points.get(i))); //Gives an error
writer.println(naiveNearestPoints(points.get(i)));//**updated** correct way to do it

Is there any other way I could write floating points to a file in a readable format?

smriti
  • 1,073
  • 1
  • 13
  • 25

2 Answers2

2

PrintWriter does support writing floating point values: print(float) and print(double).

David Conrad
  • 15,432
  • 2
  • 42
  • 54
0

What do you mean by this?

it does not support writing floating points

The PrintWriter can, in fact, print(float) or print(double)


If that isn't working for you, then if you can System.out.print a floating point, you can almost as easily write to a file by redirecting System.out into a File.

For example

File out = new File("out.txt");
try {
    System.setOut(new PrintStream(out));
} catch (Exception e) {
     e.printStackTrace();
}

// loops over list, print with System.out.print
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • I was trying to do something like this PrintWriter writer = new PrintWriter("NaiveSolution.txt"); writer.write(naiveNearestPoints(points.get(i))); And since that was giving me an error so I thought I couldn't write floating points using PrintWriter. But now I get it and thanks! – smriti Feb 25 '17 at 18:44
  • You didn't show code in the question. My answer is just an example of writing to a file, which there are several ways to do in Java – OneCricketeer Feb 25 '17 at 18:46
  • My bad, I should've done that. Sorry and thanks again! – smriti Feb 25 '17 at 18:47
  • 1
    This ruins the ability to print to the terminal for no benefit. It's a very bad idea to use `System.setOut` here rather than just making a new `PrintWriter` or `PrintStream` and using that directly. – Chai T. Rex Feb 25 '17 at 19:03
  • @Chai So? It's just a simple example. Not like I run this in production – OneCricketeer Feb 25 '17 at 19:04
  • People coming here actually use the code examples in answers. Yours has a huge drawback for literally no reason and no warning about that. The code in the edited question is two lines and doesn't have that drawback. – Chai T. Rex Feb 25 '17 at 19:13
  • @Chai I'm not here to argue, so I accept your downvote. Please carry on. – OneCricketeer Feb 25 '17 at 19:19
  • @Chai People coming here certainly shouldn't use any code from an answer without understanding what it does. – David Conrad Mar 02 '17 at 04:20
  • Besides, the question only asked "Is there any other way I could write floating points to a file in a readable format?"... And I showed there is another way. – OneCricketeer Mar 02 '17 at 04:27