I'm struggling with very basic problem, please take a look:
Some other process creates a file(only one) with unknown name but with .txt extension. This creation may take a while so I have written a loop which waits for this file and it breakes when the file is found. The problem is- how can I pass the unknown value to the String? I suppose that it is possible to do it with a regular expression.
What is more I have tried with this: Java: Find .txt files in specified folder but in my opion there is a better way to apply different solution to my case.
Code:
import java.io.File;
public class Test {
public static void waitForFile() throws InterruptedException{
while(true){
File f = new File("C:\\Test\\strangeName.txt");
if(f.exists()){
System.out.println("File is available now! End of the program");
break;
}
System.out.println("File still does not exist.");
Thread.sleep(5000);
}
}
public static void main(String[]args) throws InterruptedException{
waitForFile();
}
}
I would like to have a code which runs like this:
File f = new File("C:\\Test\\*.txt");
Thanks a lot in advance for any hints!
SOLUTION OF THIS PROBLEM
Thanks to @JordiCastilla I have created a code below. Once again thanks a lot :)
import java.io.File;
import java.io.FileFilter;
class TextFileFilter implements FileFilter{
private String fileExtension = "txt";
@Override
public boolean accept(File file) {
if(file.getName().toLowerCase().endsWith(fileExtension)){
return true;
}
return false;
}
}
public class Test {
public static String waitForFileAndGetName() throws InterruptedException{
TextFileFilter tff = new TextFileFilter();
File f = new File("C:\\Users\\502532974\\Desktop\\Tescior");
int i = 1;
while(true){
File[] files = f.listFiles(tff);
if(files.length > 0){
System.out.println("File is available now! End of the program.");
return f.listFiles(tff)[0].getName();
}
System.out.println("File still does not exist. Iteration number "+i);
Thread.sleep(5000);
i++;
}
}
public static void main(String[]args) throws InterruptedException{
System.out.println("File name is="+waitForFileAndGetName());
}
}