My code won't compile. I think it has to do with directory path, because I keep getting error message. I am trying to print out my sample directory( SampleDir) located in Desktop. Can someone help me with the directory path? Thank you in advance!
public class WalkDirectory {
public static void main(String[] args) {
File [] files = new File("C:/SampleDir").listFiles();
showFiles(files);
}
private static void showFiles(File[] files) {
for(File file: files) {
if(file.isDirectory()) {
System.out.println("Directory: " + file.getName());
showFiles(file.listFiles()); // files from the existing directory or current directory
}
else {
System.out.println("File: " + file.getName());
}
}
}
Your } characters are misplaced.
The code wad edited and in the edited code, it misses a } character at the end. For info, in the original, one was misplaced and another was missing (the last) I believe.
Try that :
import java.io.File;
public class WalkDirectory {
public static void main(String[] args) {
File[] files = new File("C:/SampleDir").listFiles();
showFiles(files);
}
private static void showFiles(File[] files) {
for (File file : files) {
if (file.isDirectory()) {
System.out.println("Directory: " + file.getName());
showFiles(file.listFiles()); // files from the existing directory or current directory
}
else {
System.out.println("File: " + file.getName());
}
}
}
}
EDIT
Exception in thread "main" java.lang.NullPointerException at
WalkDirectory.showFiles(WalkDirectory.java:16) at
WalkDirectory.main(WalkDirectory.java:11)
I suppose that the NPE is triggered in the foreach
for (File file : files)
because files array is nulL.
You should write that to check that the folder exists :
public static void main(String[] args) {
final File dirWithFiles = new File("C:/SampleDir");
//check folder exist and is a directory
if (!dirWithFiles.exist()) {
System.out.println("dir " + dirWithFiles + " does not exit");
return;
}
if (!dirWithFiles.isDirectory()) {
System.out.println("dir " + dirWithFiles + " is not a directory");
return;
}
// end check
File[] files = dirWithFiles.listFiles();
showFiles(files);
}
If the folder control fails, you should check in your filesystem that the input folder used in the application exists.
If you are in Windows env, I think the problem is in how you declare the path: "C:/SampleDir"..
Try with something like that:
String path = "C:\\Documents and Settings\\Your User\\Desktop\\SampleDir";
File[] files = new File(path).listFiles();
Related
The problem statement is, you have to list the name of the files from the given directory, you have given one directory structure which has some subdirectory and some file in them.
I did some part of the code but it is not working can you please help me what is the correct way of doing it.
code
public class Test {
public static void main(String[] args) {
RunableExample run = new RunableExample();
Thread th = new Thread(run, "thread1");
String directoryName = "C:\\Users\\GUR35893\\Desktop\\CleanupMTM";
File directory = new File(directoryName);
File[] fList = directory.listFiles();
RunableExample.MyList = new ArrayList<File>();
for (File file : fList) {
RunableExample.MyList.add(file);
}
try {
th.start();
} catch (Exception e) {
}
}
}
public class RunableExample implements Runnable {
public static List<File> MyList;
int count = 0;
File filepath;
public void run() {
try {
while (count < MyList.size()) {
System.out.println(Thread.currentThread().getName() + ">>>>"
+ MyList.size() + " >>>>> " + count);
filepath = MyList.get(count);
if (filepath != null && filepath.isFile()) {
System.out.println(Thread.currentThread().getName() + " >>"
+ filepath.getAbsolutePath());
} else {
synchronized (this) {
if (filepath != null) {
// System.out.println("Else");
RunableExample run3 = new RunableExample();
Thread th3 = new Thread(run3, "thread" + count);
File[] fList = filepath.listFiles();
// System.out.println("Else1");
for (File file : fList) {
MyList.add(file);
}
th3.start();
}
}
}
count++;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
}
If you have a directory (including sub-directories) and you want list all files.
The simplest yet effective approach would be iterate through a directory, there will be just 2 options either its a file or its a directory.
If it's a file, simply name it, don't spawn a new thread for it.
If it's a directory, spawn a new thread and re-use the same code for traversing the files or sub-directories in that directory in the newly spawned thread.
If you could give a sample output then maybe we can help further. But till then, I don't see any use of synchronization in the code.
Implementation of #Himanshu Answer.
import java.io.File;
class Lister extends Thread{
String basepath;
Lister(String basepath){
this.basepath = basepath;
}
#Override
public void run(){
File rootDir = new File(basepath);
for(File f : rootDir.listFiles()){
if(f.isDirectory())
new Lister(f.toString()).start();
else
System.out.println(f);
}
}
}
class Main {
public static void main(String[] args) {
new Lister("/").start();
}
}
This code works, but make sure it don't memory overflow for huge directory trees. For that you can add extra checks to spawn only directory you need.
I am trying to program a small utility program using java that will delete temp files, recent places etc. When i try to list files of C:\Users\Username\Recent to delete them but it is returning null.
This is what I have tried so far:
public class Simpledeleter {
public static void main(String[] args) {
File folder=new File("C:\\Users\\hp\\Recent");
deleteFolder(folder,false);
}
public static void deleteFolder(File folder,boolean flag) {
File[] files = folder.listFiles();
if(files!=null) {
for(File f: files) {
System.out.println("accessed folder!");
if(f.isDirectory()) {
System.out.println("deleting contents of "+f);
deleteFolder(f,true);
} else {
System.out.println("deleting file "+f);
f.delete();
}
}
}
if(files==null){
System.out.println("returned null!");
}
if(flag==true){
folder.delete();
}
}
}
Am i having permission problems here? Any help on this?
Am trying to deleting particular file in a folder starting with name TRTHIndicative_.
But files are not deleting,am using below code
testMethod(inputDir);
testMethod(outputFile);
private static void testMethod(String dirName){
File directory = new File(dirName);
// Get all files in directory
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().startsWith("Indicative_")) {
// Delete each file
if(file.exists()){
System.out.println("File is there!");
}
if (file.delete()) {
// Failed to delete file
System.out.println("Failed to delete " + file);
} else {
System.out.println("Deleted file succsfully");
}
}
}
please check and let me know if anything wrong.
You have your if and else confused - File#delete() returns true if the file is successfully deleted. So, the condition should be reversed:
if (file.delete()) {
System.out.println("Deleted file succesfully");
} else {
// Failed to delete file
System.out.println("Failed to delete " + file);
}
Mureinik is right.
I just tried your peace of code. It works fine. Just do the changes as follows:
public class Main {
public static void main(String[] args) {
File directory = new File("C:/temp");
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().toLowerCase().startsWith("blub")) {
// Delete each file
if (file.exists()) {
System.out.println("File is there!");
}
if (file.delete()) {
System.out.println("Deleted file succsfully");
} else {
// Failed to delete file
System.out.println("Failed to delete " + file);
}
}
}
}
}
Note the toLowerCase() I added. It will make your snippet easier to use.
I think you have permission error in the file you try to delete.
elToro`s answer is working fine with me as well.
Try to give read/write permission to every user
how to change file permissions in windows
This program works fine while I search for something inside my /home/meow directory and lists all the files, but when I try to list all the files on my system's "/" it crashes after it prints the contents of the /bin directory. I also tried to execute it as SUDO java pin
import java.io.*;
public class Pin
{
public static void printFiles(String a)
{
File dir = new File(a);
for(File file:dir.listFiles())
{
if(file.isFile())
{
System.out.println(file);
}
else
{
printFiles(file.toString());
}
}
}
public static void main(String[] args)
{
printFiles("/");
}
}
This was my output ...
vikkyhacks java # sudo java Pin
/lib64/ld-linux-x86-64.so.2
/bin/ntfsmove
/bin/init-checkconf
/bin/chown
/bin/mt-gnu
/bin/ntfs-3g.usermap
/bin/mountpoint
/bin/plymouth
/bin/s
/bin/bunzip2
/bin/gzexe
/bin/fgconsole
/bin/ntfstruncate
/bin/i
/bin/plymouth-upstart-bridge
/bin/fgrep
/bin/ping
/bin/lesspipe
/bin/rbash
/bin/gzip
/bin/ntfsmftalloc
/bin/lowntfs-3g
/bin/tailf
/bin/bzcat
/bin/tempfile
/bin/domainname
/bin/touch
/bin/zcmp
/bin/mktemp
/bin/nano
/bin/unicode_start
/bin/ln
Exception in thread "main" java.lang.NullPointerException
at Pin.printFiles(Pin.java:9)
at Pin.printFiles(Pin.java:17)
at Pin.printFiles(Pin.java:17)
at Pin.main(Pin.java:23)
You need to check that a valid array of files are returned from File#listFiles. This can happen in the case of so-called logical files where the file is actually a view of physical files:
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
...
Alternatively you can just process anything this that is a directory
public static void printFiles(String a) {
File[] files = new File(a).listFiles();
if (files != null) {
for (File file: files) {
if (file.isFile()) {
System.out.println(file);
} else if (file.isDirectory()) {
printFiles(file.toString());
}
}
}
}
Your need to check whether the file or directory is exists, by using
File file = new File(a);
if (file.exists()){
for(File file:dir.listFiles())
{
if(file.isFile())
{
System.out.println(file);
}
else
{
printFiles(file.toString());
}
}
}
I need to write a recursive algorithm to display the contents of a directory in a computer's file system but I am very new to Java. Does anyone have any code or a good tutorial on how to access a directory in a file system with Java??
You can use the JFileChooser class, check this example.
Optionally you can also execute native commands like DIR , lsusing java , here is an example
This took me way too long to write and test, but here's something that should work.
Note: You can pass in either a string or file.
Note 2: This is a naive implementation. Not only is it single-threaded, but it does not check to see if files are links, and could get stuck in an endless loop due to this.
Note 3: The lines immediately after comments can be replaced with your own implementation.
import java.io.*;
public class DirectoryRecurser {
public static void parseFile(String filePath) throws FileNotFoundException {
File file = new File(filePath);
if (file.exists()) {
parseFile(file);
} else {
throw new FileNotFoundException(file.getPath());
}
}
public static void parseFile(File file) throws FileNotFoundException {
if (file.isDirectory()) {
for(File child : file.listFiles()) {
parseFile(child);
}
} else if (file.exists()) {
// Process file here
System.out.println(file.getPath());
} else {
throw new FileNotFoundException(file.getPath());
}
}
}
Which could then be called something like this (using a Windows path, because this Workstation is using Windows):
public static void main(String[] args) {
try {
DirectoryRecurser.parseFile("D:\\raisin");
} catch (FileNotFoundException e) {
// Error handling here
System.out.println("File not found: " + e.getMessage());
}
}
In my case, this prints out:
File not found: D:\raisin
because said directory is just one I made up. Otherwise, it prints out the path to each file.
Check out Apache Commons VFS: http://commons.apache.org/vfs/
Sample:
// Locate the Jar file
FileSystemManager fsManager = VFS.getManager();
FileObject jarFile = fsManager.resolveFile( "jar:lib/aJarFile.jar" );
// List the children of the Jar file
FileObject[] children = jarFile.getChildren();
System.out.println( "Children of " + jarFile.getName().getURI() );
for ( int i = 0; i < children.length; i++ )
{
System.out.println( children[ i ].getName().getBaseName() );
}
If you need to access files on a network drive, check out JCIFS: http://jcifs.samba.org/
check this out buddy
http://java2s.com/Code/Java/File-Input-Output/Traversingallfilesanddirectoriesunderdir.htm
public class Main {
public static void main(String[] argv) throws Exception {
}
public static void visitAllDirsAndFiles(File dir) {
System.out.println(dir);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
visitAllDirsAndFiles(new File(dir, children[i]));
}
}
}
}
For each file you need to check if it is a directory. If it is, you need to recurse. Here is some untested code, which should help:
public void listFiles(File f){
System.out.println(f.getAbsolutePath());
if(f.isDirectory()){
for (File i : f.listFiles()){
listFiles(i);
}
}
}