-1

I'm working on a project where I have to use the last created file.

For example, when I run the application I have only file1 so the application uses only this file and when I create a new file2 I want that the application moves from using file1 to file2 automatically.

I hope that you help me.

Ivan Aracki
  • 4,861
  • 11
  • 59
  • 73

3 Answers3

0

You can try to get the list of files using the File directory = new File("<path>"); method. Then you can use a Comparator or Comparable to sort using Collections.sort() or Arrays.sort() the files in descending order by using the last modified date method. The last part would be just to pick the top file of the array.

Sample code:

File parentDirectory = new File("some path"); 

File[] files = parentDirectory.listFiles();

Arrays.sort(files, <Your Custom Comparator>);

File latestFile = files[0]
Sid
  • 4,893
  • 14
  • 55
  • 110
0

Extract or the files and sort them by date.

If you can use the update time you can access directly the File class using the method lastModified:

A long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970)

If you need the creation date you can get it as:

Path file = ...;
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);

// attr.creationTime() has the creation time
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

You gave practically no information on your application. Is this file used by one class only? By one instance only? Is it used across all the application?

The last one (used across all the application) is the most general scenario, and I am going to assume it.

The way I would handle is having a Singleton class that provides files. The singleton is a class of which only one instance exists and it is shared between all the application.

This class can implement, other than the attributes and methods needed by the Singleton, can have an attribute "file" that keeps track of the last file used.

Something like:

class Singleton {
  private static File lastFile; // Tracks the last file
  public static File getFile(){return lastFile;}
  public static File newFile(String path) { lastFile = new File(path); return lastFile;}
}
Tu.Ma.
  • 1,325
  • 10
  • 27