Get the current path to the java file that is running

I am trying to write a simple tcp client / server application that copies a file. I want the server to list the files that the client can copy. My code is still like 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());  
        }
    }
}

Conclusion:

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

My problem is that it gives me the parent directory instead of the current directory. My GetFileList.java is in C:\Users\XXXXX\Documents\NetBeansProjects\Test\src, but it shows. C:\Users\Alick\Documents\NetBeansProjects\TestCan someone help me fix this?

+5
source share
2 answers

The code is working correctly. This does not give you the location of the source file. It gives you the current directory in which your program is running.

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

src, new File("src").listFiles(), , : .

, - , . ,

java -cp YOUR-CLASSPATH MyClass c:/root

, c:\root.

+3

file = ( "." ); . .

, Netbeans , Project Properties → Run

0
source

All Articles