0

I'm trying to get a file to work to display its name, containing folder, size and time it was last modified. While I've written it in a working state, I don't have it working exactly as I would like. Here is the code I have written for it:

import java.nio.file.*;
import java.nio.file.attribute.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.util.*;
import java.text.*;

public class FileStatistics
{
public static void main(String[] args)
{

    try
    {
        File f = new File("C:\\Java\\Chapter.13\\TestFile.txt");
        String fileName = f.getName();
        long fileSize = f.length();
        long lastModified = f.lastModified();
        System.out.println("The file's name is: " + fileName);
        System.out.println("The file's folder location is: " + f.getPath());
        System.out.println("The file's size is: " + fileSize + " bytes");
        Date d = new Date(lastModified);
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
        System.out.println("The file was last modified: " + sdf.format(d));
    }
    catch(Exception e)
    {
        System.out.println("IO Exception");
    }
}
}

I know I have the folder's location set to simply get its path, where you can see it System.out.println("The file's folder location is: " + f.getPath()); but how exactly would I write the program to simply have it display the folder it's in? What is it exactly that I'm missing here? Thanks.

1 Answers1

0

getPath() returns the absolute path. i.e C:\Java\Chapter.13\TestFile.txt

In order to print the folder name use getParentFile().getName()

System.out.println("The file's folder is: " + f.getParentFile().getName());

In order to print the folder path use getParentFile()

System.out.println("The file's folder location is: " + f.getParentFile());
Arun George
  • 1,167
  • 3
  • 15
  • 29