0
int it_number = 1;
public void write() throws IOException {
       StringBuffer sb = new StringBuffer(name);
       sb.append(it_number);
       System.out.println(sb); 
       it_number++;


      File file = new File(sb + ".txt");
      file.createNewFile();
      FileWriter writer = new FileWriter(file);




      writer.write(results[0] + " " + results[1] + " " + velocity + "\n"     );


     writer.flush();
     writer.close();

    }
}

The String 'name' is a user input. And the iteration number 'it_number' is supposed to increment every time the same user repeats this with the same so I can a few different files with the same name. But this keeps rewriting the file over and over. What can I do to make each iteration different?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
msd
  • 11
  • 6
  • Can you share with us the code that does the iteration? (a for loop perhaps?) – GuiSim Aug 08 '16 at 19:15
  • You have to save the file number in another file. You read the other file, increment the value by 1, and write the new value to the file. Otherwise, the way your code is written, you will create file 1 every time you run your code. – Gilbert Le Blanc Aug 08 '16 at 20:01
  • Yeah but i will need the number in the file name to increment not inside the file – msd Aug 08 '16 at 20:55
  • side note: StringBuilder, builder, builder (not StringBuffer), see http://stackoverflow.com/questions/355089/difference-between-stringbuilder-and-stringbuffer –  Aug 10 '16 at 18:52
  • I would test if the file exists before writing, the counter *might* be wrong (maybe you could list the files or "write down" the counter to the filesystem) –  Aug 10 '16 at 18:54

1 Answers1

1

Try:

static int it_number = 1;

You probably are creating a new object for each write. The static will make all objects share the value.

Note this is will only be unique for a single run of the program. If you want more just use file_<date_time_stamp>.

GC_
  • 448
  • 4
  • 23
  • 1
    Note this is will only be unique for a single run of the program. If you want more just use file_. – GC_ Aug 10 '16 at 18:53
  • While you probably identified the cause of the problem, properly managing the object's lifecycle would be a much better solution. – erickson Aug 10 '16 at 19:52