Reputation: 1468
I was trying to write a methods to get all directories and files in a directory and finally decided to give up and ask here.
I know this has been asked a few times and has been answered but this is a little harder.
I did get this code
public static void listf(String directoryName, ArrayList<File> files)
{
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList)
{
if (file.isFile())
{
files.add(file);
} else if (file.isDirectory())
{
listf(file.getAbsolutePath(), files);
}
}
System.out.println(files);
}
and it helped a lot but i need it to also give the directory it was in ei.
C:\\Users\\UserName\\Desktop\\Folder\\Folder1\\a.txt
C:\\Users\\UserName\\Desktop\\Folder\\Folder1\\b.txt
C:\\Users\\UserName\\Desktop\\Folder\\Folder2\\c.txt
My first code:
public class FileTransfer
{
private final static File testFileFolder = new File("C:\\Users\\Melaia\\Desktop\\Send\\");
private static File[] filesInFolder;
private static String[] listOfFilesInFolder;
private static int noOfFilesInFolder, k = 0;
public static void startupFileSend()
{
filesInFolder = testFileFolder.listFiles();
noOfFilesInFolder = (filesInFolder.length);
for(int zzz = 0; zzz <= noOfFilesInFolder; zzz++)
{
if(filesInFolder[k].isDirectory())
{
File[] file1 = filesInFolder[k].listFiles();
listOfFilesInFolder[k] = file1[k].getName() + ";";
}
else
{
listOfFilesInFolder[k] = filesInFolder[k].getName();
}
System.out.println(listOfFilesInFolder[k]);
}
}
}
but that gives me this exception:
Exception in thread "main" java.lang.NullPointerException
at Com.org.FileTransfer.startupFileSend(FileTransfer.java:32)
at Com.org.Main.main(Main.java:7)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Please can someone give me any advice on this.
Thanks Luke.
Upvotes: -1
Views: 182
Reputation: 121692
Since you are using Java 7, don't bother and use a FileVisitor
.
Create a class, even anonymous, to manage all files in your directory, the Files.walkFileTree()
method will walk the file for you and execute the code you have put in the visitor on the different events.
You may also extend SimpleFileVisitor
instead. You can see two examples of visitors (one for recursive copy, another for recursive deletion) here.
Since you seem to want to upload, you'll probably want also to use Files.copy()
, which can take a source path and send its content to an OutputStream
.
Upvotes: 1
Reputation: 39437
1) initialize this one listOfFilesInFolder
like this
listOfFilesInFolder = new String[noOfFilesInFolder]
2) Not sure if this is the only problem but change
zzz <= noOfFilesInFolder
to
zzz < noOfFilesInFolder
3) Also, you never change the k
variable, not sure if that's intended.
Upvotes: 2