How to make Java list only writable files - java

I need to know how to know how to make Java's File.list(); method list only the files I am able to access or how to filter them out, cause now it lists files like $RecycleBin or Documents and Settings (I am on Win7) basically files I am unable to see in Win Explorer. Many Thanks.

The following will do it:
File[] subDirs = dir.listFiles( new FileFilter() {
#Override public boolean accept( File f ) {
return f.canWrite();
} } );
You could also use CanWriteFileFilter of apache.commons.io (http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/filefilter/CanWriteFileFilter.html)
Example, showing how to print out a list of the current directory's writable files:
File dir = new File(".");
String[] files = dir.list( CanWriteFileFilter.CAN_WRITE );
for ( int i = 0; i < files.length; i++ ) {
System.out.println(files[i]);
}

Related

Java - Recursively populating array of directories - avoiding NullPointerException when accessing system protected folder [duplicate]

File f=new File("C:/");
File fList[] = f.listFiles();
When i use this it list all system file as well as hidden files.
and this cause null pointer exception when i use it to show in jTree like this:
public void getList(DefaultMutableTreeNode node, File f) {
if(f.isDirectory()) {
DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
node.add(child);
File fList[] = f.listFiles();
for(int i = 0; i < fList.length; i++)
getList(child, fList[i]);
}
}
What should i do so that it do not give NullPointerException and show only non hidden and non system files in jTree?
Do this for hidden files:
File root = new File(yourDirectory);
File[] files = root.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return !file.isHidden();
}
});
This will not return hidden files.
As for system files, I believe that is a Windows concept and therefore might not be supported by File interface that tries to be system independent. You can use Command line commands though, if those exist.
Or use what #Reimeus had in his answer.
Possibly like
File root = new File("C:\\");
File[] files = root.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
Path path = Paths.get(file.getAbsolutePath());
DosFileAttributes dfa;
try {
dfa = Files.readAttributes(path, DosFileAttributes.class);
} catch (IOException e) {
// bad practice
return false;
}
return (!dfa.isHidden() && !dfa.isSystem());
}
});
DosFileAttributes was introduced in Java 7.
If running under Windows, Java 7 introduced DosFileAttributes which enables system and hidden files to be filtered. This can be used in conjunction with a FileFilter
Path srcFile = Paths.get("myDirectory");
DosFileAttributes dfa = Files.readAttributes(srcFile, DosFileAttributes.class);
System.out.println("System File? " + dfa.isSystem());
System.out.println("Hidden File? " + dfa.isHidden());
If you are trying to list all files in C:/ please keep in mind that there are other files also which are neither hidden nor system files, but that still won't open because they require special privileges/permissions. So:
String[] files = file.list();
if (files!=null) {
for (String f : files) open(f);
}
So just compare if the array is null or not and design your recursion in such a way that it just skips those files whose array for the list() function is null.
private void nodes(DefaultMutableTreeNode top, File f) throws IOException {
if (f.isDirectory()) {
File[] listFiles = f.listFiles();
if (listFiles != null) {
DefaultMutableTreeNode b1[] = new DefaultMutableTreeNode[listFiles.length];
for (int i = 0; i < b1.length; i++) {
b1[i] = new DefaultMutableTreeNode(listFiles[i].toString());
top.add(b1[i]);
File g = new File(b1[i].toString());
nodes(b1[i], g);
}
}
}
Here is the code I used to create a window file explorer using jtree.

Finding all the files of a certain extension in a project's source folder

Hello I am trying to retrieve the names of all the files of the type .mp3 from a source folder(below)
Below is the code I am using to differentiate the file type and add to the list. However I do not know which parameter I should enter into the directory it should be music folder however I do not know how to represent this.
File dir = new File("");
String[] files = dir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".mp3");
};
});
for(int a = 0; a < files.length; a++)
{
musicList.add(files[a]);
}
Try this.
List<String> result = Files.find(Paths.get("music"), 100,
(p, a) -> p.toString().toLowerCase().endsWith(".mp3"))
.map(path -> path.toString())
.collect(Collectors.toList());
if you are using Servlet :
ServletActionContext.getServletContext().getRealPath("music");
if using Spring :
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("music").getFile());
System.out.println(file.getAbsolutePath());
For javafx see this:
How to target a file (a path to it) in Java/JavaFX

Recursive search function for windows dictornaries. How?

I have an assignment where I have to use a recursive method to find any file in the dictionary i "stand in right now". The dictionary is shown in a listview and you can navigate back and forth through the folders in the GUI
Example: If i stand in C:/User/Me/ in the dictionary navigator in my GUI and then I type "hello" in the textfield of my gui, then the program must search for a file named "hello" in -> C:/User/Me/. I tried to solve the problem but ended up in a big mess and now I need some help and guide
The recurisve method that shall be used is this which work in console:
public static String findHolger(File dir, String search) {
if (dir.getName().contains((search))) {
System.out.println(dir.getPath());
}
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
// System.out.println(files[i]);
if (files[i].getName().contains(search)) {
System.out.println(files[i]);
}
}
return search;
}
This is what i have tried so far with anyout any succes:
public void findholger() {
//this method executes when search button is pressed
File dir = new File("C:/");
File[] files = dir.listFiles();
lvwMappesys.getItems().setAll(files);
String result, q;
q = txf.getSelectedText().trim();
File file1 = lvwMappesys.getSelectionModel().getSelectedItem();
if (lvwMappesys.getSelectionModel().getSelectedItem().getAbsolutePath() != null) {
}
File[] files = file1.listFiles();
for (int i = 0; i < files.length; i++) {
// System.out.println(files[i]);
if (files[i].getName().contains(q)) {
System.out.println(files[i]);
}
if (files[i].isDirectory()) {
}
}
}
As far as I understood your ListView has items which are the directory names. So you take the selected item and obtain its absolute path as Path type. You can then do the following (Note: contains Java 8 code)
Files.walk(path)
.filter(Files::isRegularFile)
.filter(path -> path.toAbsolutePath().toString().contains("hello"))
.forEach(System.out::println);
This will recursively search for files which have "hello" in their names or parent directory names. You can easily modify the filter() method to fit your needs, i.e. if you need files which are named "hello" but not the directory names, etc.

find picture in folder withot extension

how can I get all files in folder only by name without extension file?
for example I have picture name "pic1" and I don't know extension it can be "gif","jpeg","png"
I tried that but it's also looking for extension:
File dir = new File("...");
String[] files = dir.list(new NameFileFilter("pic1"));
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
thank,
String[] files = dir.list(new FilenameFilter() {
#Override
boolean accept(File dir, String name) {
//return name.startsWith("pic1.");
return name.matches("(?i)pic1\\.(gif|jpg|jpeg|png)");
}
});
Java 8:
String[] files = dir.list((dir, name) -> name.startsWith("pic1."));
List the files without providing a filter, then loop on the list: if fileNameString.startsWith("pic1") then do your logic.
To do this more correctly, use FilenameUtils.removeExtension() from Apache Commons IO (on the file name).
Since you're already using the Apache library, try:
FileFilter fileFilter = new WildcardFileFilter("pic1.*");
String[] files = dir.list(fileFilter);

Java: How to read directory folder, count and display no of files and copy to another folder?

I have to read a folder, count the number of files in the folder (can be of any type), display the number of files and then copy all the files to another folder (specified).
How would I proceed?
i Have to read a folder, count the number of files in the folder (can
be of any type) display the number of files
You can find all of this functionality in the javadocs for java.io.File
and then copy all the files to another folder (specified)
This is a bit more tricky. Read: Java Tutorial > Reading, Writing and Creating of Files
(note that the mechanisms described there are only available in Java 7 or later. If Java 7 is not an option, refer to one of many previous similar questions, e.g. this one: Fastest way to write to file? )
you have all the sample code here :
http://www.exampledepot.com
http://www.exampledepot.com/egs/java.io/GetFiles.html
File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
String filename = children[i];
}
}
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
};
children = dir.list(filter);
// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
The copying http://www.exampledepot.com/egs/java.io/CopyDir.html :
// Copies all files under srcDir to dstDir.
// If dstDir does not exist, it will be created.
public void copyDirectory(File srcDir, File dstDir) throws IOException {
if (srcDir.isDirectory()) {
if (!dstDir.exists()) {
dstDir.mkdir();
}
String[] children = srcDir.list();
for (int i=0; i<children.length; i++) {
copyDirectory(new File(srcDir, children[i]),
new File(dstDir, children[i]));
}
} else {
// This method is implemented in Copying a File
copyFile(srcDir, dstDir);
}
}
However is very easy to gooole for this stuff :)
I know this is too late but below code worked for me. It basically iterates through each file in directory, if found file is a directory then it makes recursive call. It only gives files count in a directory.
public static int noOfFilesInDirectory(File directory) {
int noOfFiles = 0;
for (File file : directory.listFiles()) {
if (file.isFile()) {
noOfFiles++;
}
if (file.isDirectory()) {
noOfFiles += noOfFilesInDirectory(file);
}
}
return noOfFiles;
}

Categories

Resources