Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save the data into File in java?

Tags:

java

io

file-io

I have one problem, that is I have one string of data and I want to save it into a separate file every time. Please give me a suggestion.

Thanks, vara kumar.pjd

like image 555
varakumar.pjd Avatar asked Dec 02 '25 08:12

varakumar.pjd


1 Answers

Use a timestamp in the filename so you can be sure it is unique. Below example uses a timestamp in milliseconds which should be enough in most cases.

If you expect you can have multiple files within 1 millisecond then you could do something with a GUID/UUID. Note that GUID/UUID could result in duplicates too, however this chance is extremely rare.

import java.io.*;
class FileWrite 
{
   public static void main(String args[])
  {
      try{
    // Create file 
    FileWriter fstream = new FileWriter(System.currentTimeMillis() + "out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
    out.write("Hello Java");
    //Close the output stream
    out.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}
like image 55
Mark Baijens Avatar answered Dec 03 '25 23:12

Mark Baijens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!