0

I've got some problems trying to print available directories on the screen.

Here's some code with two possible ways to print it:

File f = new File(System.getProperty("user.home"));

System.out.println(java.util.Arrays.toString(f.list())); //the FIRST way

for (String fileName : f.list()) {  //the SECOND
    System.out.println(fileName);   // way
}

Looks like it's a pretty good way to print directories but it prints more directories than really exist.

Thus I have to 2 questions: How to print it correctly? How to print it correctly but from another directory, not from "user.home"?

UPD!!! Ok guys, I've just found out that the problem is that it shows even hidden directories. So now please help me to print not hidden directories only.

18
  • but it prints more directories than really exist sure? How to print it correctly but from another directory ... provide a different directory in new File("/path/blub"). Commented Sep 29, 2014 at 15:16
  • Do you only want directories? Because you're printing all the files as well as the directories. Commented Sep 29, 2014 at 15:17
  • I'm almost sure, mb there some invisible directories? But my default Windows 8.1 folder search can't find anything Commented Sep 29, 2014 at 15:17
  • 1
    What does it print? Commented Sep 29, 2014 at 15:19
  • 1
    Those files all look like normal hidden files in Windows user directories to me. Commented Sep 29, 2014 at 15:33

2 Answers 2

2

You can use .isHidden() to determine wheter a file or directory is hidden.

Just modify Jamie's solution slightly for your needs:

for (File f : f.listFiles())
{
  if (!f.isHidden())
  {
    System.out.println(f.getName());
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's the answer I really need =) Thank You!
1

To only list directories, you will need to use f.listFiles(), and check each one in the result for isDirectory().

for (File sub : f.listFiles())
{
  if (sub.isDirectory())
  {
    System.out.println(sub.getName());
  }
}

2 Comments

Thank you. I need to print directories and files. Actually I'm trying to make ls (Unix) or DIR (Windows).
By the way. The output by DIR and by your way aren't the same. Your method prints more directories. Looks like it prints hidden dirs. But how to print not hidden ONLY? Thank You!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.