Hey.

I've got a programme that processes the files in a given directory. However, it can only run those files if the programme itself is saved in the same directory.

The error i am experiencing now is that once my programme runs, it also generates a class file which also is processed by the programme (because it's saved in the same directory.)

This causes a jam that that aborts the whole operation.

Could I process the files without saving my java programme in the same folder?

I tried saving it another folder, but the programme wasn't able to access the files, though it could list the file names.

File dir = new File("E:\\Major Project\\FinalLap\\278d.gz.txt");
     String path = dir.getAbsolutePath();
     int root = path.lastIndexOf("\\");
     String howPath = path.substring(0,root+1);
     File usePath = new File(howPath);
     String[] fileDir = usePath.list();
     if(fileDir == null)
     {
     	System.out.println("Directory Does Not Exist");
     }
      else
      {
//etc etc

Thanks again!

Edited 6 Years Ago by jemimaloh: n/a

Yes, you should be able to read a directory without putting your program in that directory. If you are able to list the files, you should also be able to access those files, but you need the path to the files in order to process them. It looks like the code you have above should work no matter where your program resides, since you refer to an absolute path in your variable called "dir". But the list of files in fileDir will only contain the filenames without the path. So you need to concatenate the path, which you are getting in your howPath variable, and the file names you get out of the fileDir array.

By the way, you can get the path with just the directories (minus the filename) this way:

String path = dir.getParentFile().getPath();

But your howPath also works.

Hey thanks for your suggestion.

someone from Java Ranch managed to tackle my problem,

Ernest Friedman-Hill

list() returns the names of the files (only), not the complete path to the file. Therefore when you open a file for reading, it only works if your current directory is the directory where the file lives. The solution is to supply the whole paths. One easy way: make "dir" an array of File, not String, and then use the listFiles() method rather than the list() method. FileReader can open a File object just as well as it can open a file using the name as a String, but the File will contain the complete path.

Hope this helps the others coming along!

This question has already been answered. Start a new discussion instead.