LurkerMcMe
LurkerMcMe

Reputation: 3

Improving file name readability in Java

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?

Upvotes: 0

Views: 34

Answers (3)

Mike B
Mike B

Reputation: 2776

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"

Upvotes: 1

JavaHopper
JavaHopper

Reputation: 5607

This should help you

File directory = new File("\\your_path");
File[] contents = directory.listFiles();
for (File f : contents) {
    System.out.println(f.getName());
}

Upvotes: 1

Scott Forsythe
Scott Forsythe

Reputation: 370

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.

Upvotes: 0

Related Questions