0

I am working on a program that must print the names of each file and subfolder in a given directory.

So far I have the following (this is just the working code):

File directory = new File( [the path] );

File[] contents = directory.listFiles();

for ( File f : contents ) 
{
    String currentFile = f.getAbsolutePath();
    System.out.println( currentFile ); 
}

This needs to be displayed to the user, who doesn't need to see the full path. How can I get the output to only be the file names?

Scott Forsythe
  • 360
  • 6
  • 18

3 Answers3

1

This should help you

File directory = new File("\\your_path");
File[] contents = directory.listFiles();
for (File f : contents) {
    System.out.println(f.getName());
}
JavaHopper
  • 5,567
  • 1
  • 19
  • 27
1

I suppose that sometimes you might not know the path base (for whatever reason), so there is a way to split the String. You just cut the part before the slash (/) and take all that's left. As you split it, there might be (and probably is) multiple slashes so you just take the last part

String currentFile;
String[] parts;
for ( File f : contents) {
    currentFile = f.getAbsolutePath();
    parts = currentFile.split("/");
    if (!parts.equals(currentFile)) {
        currentFile = parts[parts.length-1];
    }  
    System.out.println(currentFile);
}

Example:
"file:///C:/Users/folder/Desktop/a.html" goes to be "a.html"

Mike B
  • 2,756
  • 2
  • 16
  • 28
0

The file name is being printed as a simple String, meaning that it can be edited. All you have to do is use Str.replace on your path.

This code currentFile = currentFile.replace("[the path]", ""); would replace your file path with a blank, effectively erasing it.

Some code inserted correctly, such as

for ( File f : contents)
{
    currentFile = f.getAbsolutePath();
    currentFile = currentFile.replace("[the path]", "");
    System.out.println(currentFile);
}

will do this for each file your program finds.

Scott Forsythe
  • 360
  • 6
  • 18