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?
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:/rootSo, all files under
c:\rootwill be available.