How to use wildcards in filenames when reading in files - java

I'm working on an application that will read in SystemOut.Log files and process them. Sometimes archived files may be named slightly differently, such as SystemOut_10:20_09/07/2021-10:45_09/07/2021.Log. It's always of the form SystemOut(Some more text here).Log.
I had a little read up and stumbled across wildcards and came to the conclusion that if I were to pass SystemOut*.Log into my application as the filename it would work. But I was wrong.
I originally get my filename through a properties file like so.
fileName=prop.getProperty("fileName");
I then just tried to concatenate *.Log on the end.
fileName=fileName+"*.Log";
When I print out fileName it is "SystemOut*.Log" but when I pass in this filename to my method that reads files it doesn't work as no file is found with that name.
Am I making an error in the code or have I just misunderstood how wildcards work? Thanks

Try FileUtils from Apache commons-io (listFiles and iterateFiles methods):
The code you need is
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("*.Log");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}

Related

Why can't java find my file?

I'm trying to see how many of these text files exist, but even with them there, the program always says the numFiles = 0. I have the files in a folder called Levels within the src folder. Thanks
int numFiles = 0;
for(int i = 0; i < 24; i++){
File file = new File("/Levels/level" + (i+1) + ".txt");
if(file.exists()){
numFiles++;
}
}
System.out.println(numFiles);
Edited
I overlooked that DirectoryStream doesn't support count()
You could go with an absolute path and make use of Stream API and lambdas. Like so:
String dirString = "..." //absolute Path
Path dir = Paths.get(dirString);
int numFiles = dir.getNameCount();
System.out.println(numFiles);
One advantage is that you can rename the files at will as long as they stay in the same directory. If you only want to work with specific files you can use filter() like so:
Files.newDirectoryStream(dir).filter(Predicate);
or add the filter directly when creating the DirectoryStream like so:
Files.newDirectoryStream(dir, RegEx);
To do something with each File you can use the consumer forEach() or have a look at Stream JavaDoc for other consumers/intermediate operations. Also double check if the DirectoryStream supports the Stream operation you want to use.
Your path is incorrect - if you are referring to an absolute location only then start with a /.
Also if you are using an editor remember your Java files are in src but but you don't run Java File you run class files and the class files may be in your bin/build directory most likely - check if the text file are in the build or bin directory.
Your path is incorrect, if you are referring to a local file(like something in your project folder) use
File file = new File("Levels/level" + (i+1) + ".txt");
the slash you used in front of the name makes it look in the root of the drive, not the local directory.

JAVA - zip4j, extract all text files ONLY from a zip file

we can extract all the files from a zoip filder using extractAll method given in zip4j, but what if i need to extract only one kind of files,say only text files or only files which have a certain sub-string in the name of the file?? is there a way to do this using zip4j
i thought this question might be relating to my problem
Read Content from Files which are inside Zip file
but that's not exactly what i want.
can anyone explain in detail about using this ZipEntry things, if it helps my problem getting solved?
Try the below code
ZipFile zipFile = new ZipFile("myzip.zip");
// Get the list of file headers from the zip file
List fileHeaderList = zipFile.getFileHeaders();
// Loop through the file headers
for (int i = 0; i < fileHeaderList.size(); i++) {
FileHeader fileHeader = (FileHeader)fileHeaderList.get(i);
String fileName = fileHeader.getFileName();
if(fileName.contains(".java")){
zipFile.extractFile(fileHeader, "c:\\scrap\\");
}
}

Java: How to get File.listOfFiles working non-recursively on linux?

I use this piece of code to find XML files that another part of my program creates in a given directory:
String fileName;
File folder = new File(mainController.XML_FILES_LOCATION);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
fileName = listOfFiles[i].getName();
if (fileName.endsWith(".xml")) {
Document readFile = readFoundXmlFile(fileName);
if (readFile != null) {
boolean postWasSuccesful = mainController.sendXmlFile(readFile, fileName);
reproduceXmlFile(readFile, fileName, postWasSuccesful);
deleteXmlFile(fileName);
}
}
}
}
What it does is that it reads every XML file that gets placed in the given directory, it sends it to an URL and it copies it to a subdirectory (either 'sent' or 'failed' based on the boolean postWasSuccedful) and deletes the original so it won't be sent again.
In Windows this works as expected, but I've transferred the working code to a Linux machine and all of a sudden it get's in this loop of sending bla.xml and a second later sent\bla.xml and again a second later sent\sent\bla.xml followed by sent\sent\sent\bla.xml, etc.
Why is Linux deciding for itself that listFiles() is recursive?? And, better, how to prevent that? I can add an extra check in the if-statement looking for files ending with .xml that there isn't a directory-char allowed in the fileName, but that's a workaround I don't want as the amount of files in the pick-up directory will never be high whereas the amount of files in the sent subdirectory can get quite high after a while and I wouldn't want this piece of code to become slow
My psychic powers tell me that reproduceXmlFile() builds the target pathname using a hard-coded backslash ("\"), and therefore you're actually creating files with backslashes in their names.
You need to use File.separator rather than that hard-coded "\". Or use something like new File("sent", fileName).toString() to generate your output pathnames.
(Apologies if I'm wrong!)

Java - URL to File

I am trying to create a method that displays a list of files in a given directory. This works fine for normal directories (on disk) but when I enter a url my list of files is null.
public void getListOfFiles(String folderLocation){
File folder = new File(folderLocation);
File[] listFiles = folder.listFiles();
for(int i = 0; i < 10; i++){
System.out.println(listFiles[i]);
}
}
I think my problem is because the File 'folder' is removing one of the '/' in my folderLocation (http://...)
I have tried using URL and URI but have had no luck! Can anyone help?
First of all, File won't work for this as it's not networking-aware.
Secondly, in general there's no mechanism to list files over plain HTTP. If the HTTP server gives you some kind of a listing page when you present it with the URL, you'll have to download the page using, for example, URLConnection and parse it yourself.
To list files over FTP, you could use FTPClient from Apache Commons Net.

Write file in sub-directory in Android

I'm trying to save a file in a subdirectory in Android 1.5.
I can successfully create a directory using
_context.GetFileStreamPath("foo").mkdir();
(_context is the Activity where I start the execution of saving the file) but then if I try to create a file in foo/ by
_context.GetFileStreamPath("foo/bar.txt");
I get a exception saying I can't have directory separator in a file name ("/").
I'm missing something of working with files in Android... I thought I could use the standard Java classes but they don't seem to work...
I searched the Android documentation but I couldn't fine example and google is not helping me too...
I'm asking the wrong question (to google)...
Can you help me out with this?
Thank you!
I understood what I was missing.
Java File classes works just fine, you just have to pass the absolute path where you can actually write files.
To get this "root" directory I used _context.getFilesDir(). This will give you the root of you application. With this I can create file with new File(root + "myFileName") or as Sean Owen said new File(rootDirectory, "myFileName").
You cannot use path directly, but you must make a file object about every directory.
I do not understand why, but this is the way it works.
NOTE: This code makes directories, yours may not need that...
File file = context.getFilesDir();
file.mkdir();
String[] array = filePath.split("/");
for (int t = 0; t < array.length - 1; t++) {
file = new File(file, array[t]);
file.mkdir();
}
File f = new File(file, array[array.length - 1]);
RandomAccessFileOutputStream rvalue = new RandomAccessFileOutputStream(f, append);
Use getDir() to get a handle on the "foo" directory as a File object, and create something like new File(fooDir, "bar.txt") from it.

Categories