I want to list all the folders of the current directory but there are two problems. Everytime i run this program, the list shows all the files of the last folder inside the directory and the filter does not work.
Can you please help me?
public void foldersPanel()
{
JPanel folderScreen = new JPanel();
folderScreen.setLayout(new GridLayout(1,1));
direFilter = new FilenameFilter()
{
public boolean accept(File file, String string)
{
if (file.isDirectory())
{
return file.isDirectory();
}
else
{
return false;
}
}
};
File directory = new File(System.getProperty("user.dir"));
File[] listOfFiles = directory.listFiles(direFilter);
String[] allFiles = directory.list();
if (directory.isDirectory())
{
int x = 1;
for (int i =0; i<listOfFiles.length; i++) // displays all the files
{
if (listOfFiles[i].isDirectory())
{
folderList = new JList(listOfFiles[i].list(direFilter));
System.out.println(x +") Directory = " + listOfFiles[i].getName());
x++;
folderList.setSelectedIndex(1);
}
else
{
System.out.println("is file");
}
folderScreen.add(new JScrollPane(folderList));
}
}
else
{
System.out.println("This is a file, not a directory, so we will move to the parent folder");
directory = directory.getParentFile();
updateLabels();
System.out.println("The new directory is : " +directory.toString());
}
}
code
Your method isn't recursive. A directory is a tree; you want to recursively call a method that adds the list of files to an overall list if it's a directory, or simply add the file if it's a file. Keep accumulating all the lists and you'll have every file under the root directory.
The first parameter of FilenameFilter.accept is the containing directory. Effectively, your test will always return true.
[EDIT]
More specifically, I think you really want your test to be:
public boolean accept(File dir, String fileName) {
return new File(dir, fileName).isDirectory();
}
Related
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.
I'm trying to loop through a folder and list all files with a specific file ending. I'm trying to solve this problem with a recursive method but I'm not getting anywhere.
private int counter = 0;
public void printAllJavaFiles(File directory) {
printFile(directory);
File[] subDirectories = directory.listFiles();
for (File file : subDirectories) {
printAllJavaFiles(file);
}
}
private void printFile(File file) {
// Get file extension
String fileExtension = "";
int i = file.getName().lastIndexOf('.');
if (i >= 0) {
fileExtension = file.getName().substring(i + 1);
}
if (fileExtension.equals("java")) {
System.out.println("File: " + file.getName() + " Size: " + file.length());
}
}
Any suggestions? I really have no idea how to go up and down in the directory structure. It just enters the first folder and once it's done listing it's files it throws a nullpointerexception.
You should use the File.isDirectory() method. Like this:
public void printAllJavaFiles(File directory) {
if (directory.isDirectory()) {
File[] subDirectories = directory.listFiles();
for (File file : subDirectories) {
printAllJavaFiles(file);
}
}else {
printFile(directory);
}
}
Documentation on that method here: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#isDirectory()
The idea is that for every file you check if it is a folder, if so, make the recursive call. If not, simply print the file.
I'm curious as if there's a way to define a Parent-folder, then have a program cycle through all of the files, and sub-folders, and rename the file extension.
I know this can be done in the command prompt using the command "*.ext *.newext" however that's not a possible solution for me and I need to rename 2,719 file extentions that are nested inside of this folder.
Yes, you can do it. Here's an example:
// java 6
File parentDir = new File("..");
System.out.println(parentDir.getAbsolutePath());
final File[] files = parentDir.listFiles();
System.out.println(Arrays.toString(files));
// java 7+
File parentDir = new File("..");
try {
Files.walkFileTree(parentDir.toPath(), new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toFile().renameTo(new File("othername.txt"))) {
return FileVisitResult.CONTINUE;
} else {
return FileVisitResult.TERMINATE;
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
This one does not go through subdirs, but it is easy to modify that way.
Here's a simple function that should do the job for you. Sorry, if it's not the most elegant code -- my Java is a little rusty.
By default, it's recursive in its implementation; so be aware that it will affect all files of the specified type in the parent directory!
SwapFileExt params
path the parent directory you want to parse
cExt the extension type that you want to replace
nExt the desired extension type
NOTE: Both cExt and nExt are to be represented without the '.' (e.g. "txt", not ".txt")
public static void SwapFileExt(String path, String cExt, String nExt) {
File parentDir = new File(path);
File[] contents = parentDir.listFiles();
for (int i = 0; i < contents.length; i++) {
if (contents[i].isFile()) {
if (contents[i].toString().contains("." + cExt)) {
String item = contents[i].toString().replaceAll("." + cExt, "." + nExt);
contents[i].renameTo(new File(item));
}
} else if (contents[i].isDirectory()) {
SwapFileExt(contents[i].toString(), cExt, nExt);
}
}
}
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;
}
I'm trying to get a backup program to take a folder selected by the user using JFileChooser and copy it to a destination also selected using the same method.
The only problem is that it doesn't put all the contents of the selected folder into a folder in the destination named the same thing, and I really dont know why. I did some Googling, and I didnt find anything useful.
Here's the code:
package main;
import java.io.File;
import java.util.ArrayList;
public class test {
BackgroundWorker bw;
static ArrayList bgWorker = new ArrayList();
ArrayList al = new ArrayList(); // this is the list of files selected to
// back up
String dir = ""; // this is the path to back everything up to selected by
static // the user
boolean bwInitiallized = false;
public void startBackup() throws Exception {
Panel.txtArea.append("Starting Backup...\n");
for (int i = 0; i < al.size(); i++) {
/**
* THIS IS WHERE I NEED TO CREATE THE FOLDER THAT EACH BACKUP FILE
* WILL GO INTO EX: SC2 GOES INTO A FOLDER CALLED SC2 AND RIOT GOES
* TO RIOT, ALL WITHIN THE DIRECTORY CHOSEN
*/
File file = new File((String) al.get(i));
File directory = new File(dir);
// File dirFile = new File(dir + "\\" + file.getName());
// if (!dirFile.exists())
// dirFile.mkdir();
bw = new BackgroundWorker(Panel.txtArea, file, directory);
bgWorker.add(bw);
bwInitiallized = true;
bw.execute();
/**
* follows to the bottom of the txtarea
*/
int x;
Panel.txtArea.selectAll();
x = Panel.txtArea.getSelectionEnd();
Panel.txtArea.select(1, x);
}
clearList(); // method not included in this example that deletes all the
// contents of the al array list.
}
public static void cancel() {
BackgroundWorker bg;
if (bwInitiallized) {
bwInitiallized = false;
Panel.txtArea.append("Cancelling...\n");
for (int i = 0; i < bgWorker.size(); i++) {
// BackgroundWorker bg = (BackgroundWorker) bgWorker.get(i);
bg = (BackgroundWorker) bgWorker.get(i);
bg.cancel(true);
}
Panel.txtArea.append("Canceled backUp!\n");
} else {
Panel.txtArea.append("Cannot Cancel! Not Initiallized!\n");
}
}
}
What I think the problem is: I believe that for whatever reason the destination file path needs to have to the name of the folder included, but I tried that and it didnt help.
Does anyone know what I'm doing wrong?
This is the code that makes the JFileChooser:
public void fileChooserToDestination() {
LookAndFeel previousLF = UIManager.getLookAndFeel();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
}
JFileChooser jfc = new JFileChooser();
try {
UIManager.setLookAndFeel(previousLF);
} catch (UnsupportedLookAndFeelException e) {
}
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (jfc.showDialog(null, "Select Directory") == JFileChooser.APPROVE_OPTION) {
File file = jfc.getSelectedFile();
dir = file.getPath();
Panel.txtArea.append("User selected " + file.getPath()
+ " for the destination...\n");
try {
startBackup();
} catch (Exception e) {
}
} else {
Dialogs.msg("You canceled selecting a destination folder! Returning to main screen...");
al.clear();
Panel.txtArea.append("User cancelled the destination selection..."
+ "\n");
}
return;
}
Parts of the code I need are missing. I can't see where you're making your decisions about how to append the source file to the destination path, so I wrote this quick example it illustrate the point...
File sourcePath = new File("/path/to/be/backed/up");
File destPath = new File("X:/BackupHere");
// Get all the files from sourcePath
List<File> listFiles = getFilesFrom(sourcePath);
for (File toBackup : listFiles) {
// Now we need to strip off the sourcePath
// Get the name of the file
String fileName = toBackup.getName();
// Get parent folder's path
String path = toBackup.getParent();
// Remove the source path from file path
path = path.substring(sourcePath.getPath().length());
// Append the file name to the path
path = path + File.separator + fileName;
// Now we have the name of the back up file
String backupFile = destPath + path;
System.out.println("Backup to " + backupFile);
}
Basically, you need to strip of the "source path" (the directory you want to copy). You then use the resulting value to append to the "backup path" value and you should then have a suitable path.