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\Test
Can anyone help me fix this?
To determine the exact location of your current directory within the file system, go to a shell prompt and type the command pwd.
The current working directory means the root folder of your current Java project.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With