Dan
Dan

Reputation: 8513

Get current path of java file that is running

I am trying to write a simple tcp client/server app that copies a file. I want to the server to list the files the client can copy. My code so far is this:

import java.io.*;
public class GetFileList
{
    public static void main(String args[]) throws IOException{
        File file = new File(".");  
        File[] files = file.listFiles();  
        System.out.println("Current dir : " + file.getCanonicalPath());
        for (int fileInList = 0; fileInList < files.length; fileInList++)  
        {  
            System.out.println(files[fileInList].toString());  
        }
    }
}

Output:

Current dir : C:\Users\XXXXX\Documents\NetBeansProjects\Test
.\build
.\build.xml
.\manifest.mf
.\nbproject
.\src
.\UsersXXXXXDocumentsNetBeansProjectsTestsrcfile2.txt

My issue is that it is giving me the parent directory instead of the current directory. My GetFileList.java is located in C:\Users\XXXXX\Documents\NetBeansProjects\Test\src but it is showing C:\Users\Alick\Documents\NetBeansProjects\TestCan anyone help me fix this?

Upvotes: 6

Views: 22587

Answers (2)

Ashwinee K Jha
Ashwinee K Jha

Reputation: 9317

Rather than File file = new File("."); Use absolute path. You cannot depend on user launching program from specific directory.

If you want Netbeans to launch your program from specific directory you can specify the directory as working directory in Project Properties -> Run

Upvotes: 0

AlexR
AlexR

Reputation: 115388

The code works correctly. It does not give you the location of your source file. It gives you the current directory where your program is running.

I believe that you are running program from IDE, so the current directory in this case is the root directory of your project.

You can list your project src directory by calling new File("src").listFiles() but I do not think you really need this: when you compile and package your program the source and source directory are not available anyway.

I think that if you wish to be able to show some directory structure to your user your program should get the root directory as a parameter. For example you should run your program as

java -cp YOUR-CLASSPATH MyClass c:/root

So, all files under c:\root will be available.

Upvotes: 4

Related Questions