Search code examples
javar.java-file

How, when serializing, not to write an object to a specific file, but to create a new file in the selected directory always with a new name?


I am trying to serialize an object in java and subtract the given object from that file. But what I need is that I do not select a file for serialization, but that during serialization this file is created in the selected directory. That is, serialization creates a new file with an always new name

In the code, I apply the code for the selected file, but I can’t figure out how to always create a new file in the selected directory when serializing an object

public static void main(String args[]) throws IOException {
  FileOutputStream fos = new FileOutputStream("messages/FirstMessages.txt");
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  TestSerial ts = new TestSerial();
  oos.writeObject(ts);
  oos.flush();
  oos.close();
}

And also how to understand that the proofreading will be from a new file. Maybe somehow through a variable?

I am attaching the code to read from the file.

 public static void main(String args[]) throws IOException {
  FileInputStream fis = new FileInputStream("messages/FirstMessages.txt");
  ObjectInputStream oin = new ObjectInputStream(fis);
  TestSerial ts = (TestSerial) oin.readObject();
  System.out.println("version="+ts.version);
}

Solution

  • Have you checked File.createTempFile()?

    createTempFile

    public static File createTempFile(String prefix, String suffix, File directory) throws IOException

    Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:

    • The file denoted by the returned abstract pathname did not exist before this method was invoked, and
    • Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.

    This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.