How to treat java package as a File folder? - java

I want to be able to iterate through a package of files as if the package were a folder.
Something like the below (scripts being the java package):
File scriptFolder = new File("scripts").getAbsoluteFile();
The packages appear are not being treated like folders. If I hardcode the path C:\Users\...\project_folder\...\scripts the File.isFile() method returns false for the package. If I do new File (C:\Users\...\project_folder\...\scripts\script).isFile() I get true.
I want to get a File of the folder so I can get a list of the files in the folder and iterate through it.

The .isFile() method returns true only if you are referencing a plain jane normal file. If you're referencing a directory, it'd return false. Try .isDirectory() or possibly .exists().
Or don't; there's no real need:
File[] filesInDir = new File("C:\\Users\\....\\scripts").listFiles();
if (filesInDir == null) {
// this means it wasn't a directory or didn't exist or isn't readable
} else {
for (File child : filesInDir) {
// called for each file in dir
}
}

The official javadocs say this about File#isFile():
Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.
You can check if it is a directory with File#isDirectory(), then if it is, you can list its contents with File#listFiles().

Unless I'm missing something in your question C:\Users...\project_folder...\scripts is a directory so isFile() will return false because it is not a file.

Related

How do I distinguish between a file and a folder when renaming a file/folder in java

I am currently programming a file name normaliser. Files have a format and folders dont. When I rename a file I need to make sure that I do not affect the format therefore I did
fileName.substring(fileName.lastIndexOf("."),fileName.length)
thereby if I want to replace all the periods in a fileName it does not affect the format, when a folder with periods in its name goes through this process, the last instance of the period is still part of its name, therefore it does not replace all the dots in the folders name. I need to know how to distinguish between a file and a folder so I can fix this.
You can use
someFile.isDirectory();
It returns true if the file is a folder, and false if not.
You can use File.isDirectory() to test whether the file denoted by this abstract pathname is a directory. You can also use File.isFile() to test whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria.
File f = new File(fileName);
if (f.isFile()) {
// it's a file.
} else if (f.isDirectory()) {
// it's a directory.
}

Getting a file object of a directory

I need a File object pointing to a directory (may not be existing). How do I do that?
Even if I do something like
File dir = new File("/tmp/something/"); // with trailing slash
dir.isDirectory() is false. Then I tried dir.mkdir() which returns false, why? I dont need the directory to be existing, in fact, I want it to point to a directory that does not exist (I am doing testing). How can I achieve this?
from javadoc: "true if and only if the file denoted by this abstract pathname exists and is a directory"
If the file does not exists isDirectory() return false. If you are doing testing probably use a stub can be a better option, in unit testing its better try to don't touch external resources like the filesystem.
Use dir.mkdirs()
mkdirs() will create the specified directory path in its entirety where mkdir() will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create.
Trailing slash does not matter. File.isDirectory returns false because it returns true if and only if the file denoted by this abstract pathname exists and is a directory

Java and file list

I should get a list of file contained in a directory.
What I do is:
File file = new File(PATH);
for (File index:file.listFiles)
System.out.println(index.toString());
The matter is that doing this I get printed also files I shouldn't see, temporary, for example.
In my test directory I have to file: ciao and test, but when I run my code I see ciao, ciao~, test~, and also other stuff if I modify a file (I suppose they are buffer file).
So, how can I get only true file, as if I was browsing my fileSystem?
If you want to list only files whose attributes (name included) obey a set of conditions, you need to use another version of .listFiles() which takes a FileFilter as an argument. This interface has a sole accept() method which returns true if the file can be listed.
This simple example will filter out files whose name end with a ~:
file.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return !pathname.getName().endsWith("~");
}
})
If your FileFilter is more complex than the one above, consider exernalizing it to a variable (private static final if the filter will never change).
Files you don't see are probably hidden, you can check that:
File file = ...;
if(file.isHidden()){...}
use
if (!index.isHidden()) {
System.out.println(index.toString());
}
to suppress hidden files.
you further can check for
index.isDirectory()
if you dont want subdirectory to be listed.
But dont expect an method that can read your thougts what you call an real (or clean, or nice) file.
You could write yourself a filter for that, once you now what files to exclude.
See java.io.FileFilter for more.

Java isFile(), isDirectory() without checking for existence

I want to check if a given String is a file or a directory, i've tried the methods isFile() and isDirectory() of the File class but the problem is that if the directory or file doesn't exist these methods returns false, because as stated in the javadoc :
isFile() :
true if and only if the file denoted by this abstract pathname exists
and is a normal file; false otherwise
isDirectory() :
true if and only if the file denoted by this abstract pathname exists
and is a directory; false otherwise
Basically i need two methods without the exist clause ...
So i want to test if the given string complies to a directory format or complies to a file format, in a multiplatform context (so, should work on Windows, Linux and Mac Os X).
Does exist some library that provide these methods ? What could be the best implementation of these methods ?
UPDATE
In the case of a string that could be both(without extension) by default should be identified as directory, if a file with that path does not exist.
So i want to test if the given string complies to a directory format or complies to a file format, in a multiplatform context (so, should work on Windows, Linux and Mac Os X).
In Windows, a directory can have an extension and a file is not required to have an extension. So, you can't tell just by looking at the string.
If you enforce a rule that a directory doesn't have an extension, and a file always has an extension, then you can determine the difference between a directory and a file by looking for an extension.
Why not just wrap them in a call to File#exists()?
File file = new File(...);
if (file.exists()) {
// call isFile() or isDirectory()
}
By doing that, you've effectively negated the "exists" portion of isFile() and isDirectory(), since you're guaranteed that it does exist.
It's also possible that I've misunderstood what you're asking here. Given the second part of your question, are you trying to use isFile() and isDirectory() on non-existent files to see if they look like they're files or directories?
If so, that's going to be tough to do with the File API (and tough to do in general). If /foo/bar/baz doesn't exist, it's not possible to determine whether it's a file or a directory. It could be either.
Sounds like you know what you want, according to your update: if the path doesn't exist and the path has an extension it's a file, if it doesn't it's a directory. Something like this would suffice:
private boolean isPathDirectory(String myPath) {
File test = new File(myPath);
// check if the file/directory is already there
if (!test.exists()) {
// see if the file portion it doesn't have an extension
return test.getName().lastIndexOf('.') == -1;
} else {
// see if the path that's already in place is a file or directory
return test.isDirectory();
}
}
There are rules for what is invalid in a file and/or folder name. For example, Windows doesn't allow *, ?, and a few other characters. Based on what's invalid, you could build a regex expression or some other process/checking system to see if it looks like a file or folder.
This could get complex as you want it to work for many different OS's. Also, as previously posted, there would be no way to tell a file from a folder unless you artificially enforced a convention. For example, directories must end in a front-slash / in Windows.
Having the IF EXISTS check first would help. If IF EXISTS = true, then running the existing File.isDirectory() or File.isFile() code would simplify a lot of this. You would only have to write code for when IF EXISTS = false.

How to enter a directory as an argument in Eclipse

Basically, I have a directory with some files in it. In run configurations I am trying to put the directory as an arguement like so: \(workspacename\directory. Then, the following code should create a list of all the files in that directory:
String directory = args[1];
File folder = new File(directory);
File[] allFiles = folder.listFiles();
ArrayList<File> properFiles = null;
for (File file: allFiles) {
if(file.getName().endsWith(".dat")){
properFiles.add(file);
}
}
the problem i'm facing is that for some reason allFiles is null.
I'll take a guess at what your problem might be:
If your argument is a relative path (as opposed to an absolute path, staring with "/" or "c:/" for example), keep in mind that files will be relative to the working directory of the application.
So new File(directory) will be relative to wherever the application is started. In Eclipse the default working directory is in the project. So if your project is in the top level of the workspace, it will be something like workspacename/project.
You can try printing out folder.getAbsolutePath(), folder.exists() and folder.isDirectory() to help diagnose your problem.
The javadocs say listFiles() will return null if the directory does not actually exist (among other things):
Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
Debug by verifying (debugger or printf) the args[1] value.
Also, it looks like you might be trying to use a substitution variable to insert the workspace location in the path. If so, again, you need to verify (via debugger or printf) that the placeholder is getting replaced properly.

Categories

Resources