seif gamal seif gamal - 1 month ago 4
Java Question

How to output list of files names of given folder/path in java including .txt files?

I'm trying to implement

ls
command in java by this function to get all folders name in
current path
- this is of type file for sure.

private static void ls() {
File[] paths = currentPath.listFiles();
for (int i = 0; i < paths.length; i++) {
System.out.print(paths[i].getName() + "\n");
}

}


The problem is that code does not output either the
.txt
or
.pdf
, so how to solve this to make it output all folders/files of any type, or use something else instead of
listFiles()
?

Answer

Do this:

File dir = new File(System.getProperty("user.home"));
File[] filesList = dir.listFiles();

Changing user.home directory:

Setting VM argument should work:

java -Duser.home=<new_location> <your_program>

Here's a test case:

public class test {
  public static void main(String[] args) {
    System.out.println(System.getProperty("user.home"));
  }
}
Comments