checai
checai

Reputation: 926

Can run java in Eclipse but not in cmd

My situation is simple. I have this in my program:

File folder = new File("input");
File[] listOfFiles = folder.listFiles();
System.out.println(listOfFiles.length);

I just want to put all the path of files from the folder "input" to an array. It works fine by running with eclipse.When I try to do this in cmd, it gives me an null pointer exception. My java file is in this directory:

C:\Users\JHeng\Desktop\java stuff\converter\src

Thanks for responding!

If I put the absolute directory in the first line:

File folder = new File("C:\\Users\\JHeng\\Desktop\\java stuff\\converter\\src\\input");

When I run it in eclipse, eclipse even gives me a null pointer exception in the line

System.out.println(listOfFiles.length);

Thanks in advance!

Upvotes: 0

Views: 194

Answers (2)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

It obviously a problem of workspace. Now try the below code.......

But first be sure you have "src" folder on the specified path..., which is passed in File constructor as an argument below.

File folder = new File("c:\\Users\\JHeng\\Desktop\\java stuff\\converter\\src");
File[] listOfFiles = folder.listFiles();
System.out.println(listOfFiles.length);

Upvotes: 0

Andrzej Doyle
Andrzej Doyle

Reputation: 103797

The problem is going to be your working directory differs between the two cases.

The File object you create on the first line uses a relative path - so it will find a relevant folder if run from some locations and fail from others. The call to listFiles() in particular will:

return null if this abstract pathname does not denote a directory, or if an I/O error occurs.

Can you specify an absolute path instead, so that the behaviour of your program will not depend on the directory that it's executed from? (This might involve either hard-coding the directory, or else picking it up as a config variable or system property.)

If you don't want to do this, then presumably your program ought to behave differently depending on the directory it's run from (e.g. if it were to do something for all files in the current directory). If this is intended, then you can simply put in better error-handling for the case where there is no subdirectory called "input" - e.g. check that folder.isDirectory() is true, and if not output an appropriate error message.

Upvotes: 1

Related Questions