Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current path of java file that is running

Tags:

java

directory

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?

like image 801
Dan Avatar asked Feb 05 '12 10:02

Dan


People also ask

How do I see my current path?

To determine the exact location of your current directory within the file system, go to a shell prompt and type the command pwd.

What is current working directory in Java?

The current working directory means the root folder of your current Java project.

How do you check if a path is a directory Java?

File. isDirectory() checks whether a file with the specified abstract path name is a directory or not. This method returns true if the file specified by the abstract path name is a directory and false otherwise.


1 Answers

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.

like image 91
AlexR Avatar answered Sep 17 '22 11:09

AlexR