MG97 MG97 - 1 year ago 68
Java Question

Java - How do I say I don't care what this part of the string contains?

I've got a bit of code, where I get the timestamp, however I want to be able to say that I don't care what seconds it is, so... this is the code I have:

String timeStampString = new SimpleDateFormat("yyyyMMddHHmm").format(Calendar.getInstance().getTime());
File fileName = new File(universal + "/Downloads/" + timeStampString);
String newName = "allPi.csv";
if (fileName.exists()) {
fileName.renameTo(new File(universal + "/Downloads/allPi.csv"));

The downloaded file will have a full timestamp down to seconds, how do I say that I don't care what numbers are in the seconds part, like timeStampString + "**"; or something??

I've tried a few random things like:

File fileName = new File(universal + "/Downloads/" + timeStampString + "[.+]");

Can anyone help?

Answer Source

First, don't use the File class. It is an outdated, badly written class which should not be used in new code, as better alternatives have existed since Java 1.4 or so.

Instead, use Path and Files. They have many methods that allow you to do common tasks, and in addition have better error reporting.

In this particular case, you can use a DirectoryStream, which comes from the same family of classes (java.nio.file). A DirectoryStream is an iterable object of files in a directory. And the Files class allows you to get a DirectoryStream of all the files in the directory that match a glob pattern. Glob patterns are the familiar patterns like *.java or Name-xyz-?.txt.

In your case you assume that you'll have only one entry. So you just need the first entry in the associated iterator.

Path dir = Paths.get( universal, "Downloads" );
Path renameTo = Paths.get( universal, "Downloads", "allPi.txt" );
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, timeStampString + "*" )) {
    Iterator<Path> iterator = stream.iterator();
    if ( iterator.hasNext() ) {
        Path path =;
        Files.move( path, renameTo, StandardCopyOption.REPLACE_EXISTING );

Of course, have try-catch for any exceptions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download