How do I create a new file every time the method is called?
In the code below, I tried to set a method that should create files in a directory.
There are two different methods I've tried, but no files seem to be generated.
Perhaps there is a syntax problem?
public void makeNewFiles() {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss dd-MM-yyyy");
String ns = sdf.format(d);
File ntf = File.createTempFile(ns, ".png", directory);
}
public void makeNewFiles() {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss dd-MM-yyyy");
String ns = sdf.format(d);
File n1 = new File(directory, pathToActualFile);
File n2;
if(n1.exists()) {
n2 = new File(directory, ns + ".png");
n2.createNewFile();
}
}
source to share
Depending on your OS,
"hh:mm:ss dd-MM-yyyy"
may or may not be a valid filename (I would just avoid that space or : colons in there, which might give you concern in many environments). To be precise: most modern operating systems accept spaces in file names, but especially any Unix-like filesystem requires special thought when making command line calls that must deal with "spacy" names. While the colon : no longer works; at least for Windows and Unix like OS.
Then: if your code is called multiple times in the same second; your filename is still "not enough" to ensure you don't recreate the same file again.
Finally: consider adding some "header" to your string; as
ns = "whatever-" + sdf.format("hh_mm_ss_dd-MM-yyyy")
source to share