简体   繁体   中英

Java repeatedly writing doubles to txt file

I am trying to to write randomly created doubles to a txt file, but I do not know the best way of doing this since the doubles must be written to the file repeatedly

Here is my code for the Generator

public class DataGenerator 
{
  public static void main(String[] args) 
  {
    // three double values are read from command line m, b, and num
    double m = Double.parseDouble(args[0]); // m is for slope
    double b = Double.parseDouble(args[1]); // b is y-intercept
    double num = Double.parseDouble(args[2]); // num is number of x and y points to create
    double x = 0;
    double y = 0;
    for (double count = 0; count < num; count++) // for loop to generate x and y values
    {
      x = Math.random() * 100;
      y = (m * x) + b; // slope intercept to find y
      System.out.printf("\n%f , %f", x, y);
      System.out.println();
    }
  }
}

Your code says it all, you just need to replace System.out with another PrintStream that drains into a file:

PrintStream out = new PrintStream(new FileOutputStream("myfile.txt"));

Then just replace each System.out with just out .

Unlike System.out , you'll also have to close the strem when done.

There are number of thing you can use to write to a file. They basically all work the same way as System.out .. they just connect to a file instead of stdout . I would suggest taking a look at PrintWriter , IIRC that was one of the easier ones for a task like that

PrintWriter fout= new PrintWriter("OutputFile.txt");
//....
fout.printf("\n%f , %f",x,y);
fout.println();
//....
fout.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM