0

I am trying to get a list of folders from the root directory in my JSP project and then display them to the user in a table, with links to child folders and the size of the folder. The code below is to get a list of directories inside the WebContent folder.

String absolutePath = this.getServletContext().getRealPath("/") + relativePath;
String fileList = "<tr><th>File Name</th><th>Size [B]</th><th>Last Updated</th></tr>";

File folder = new File(absolutePath);
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
    if (listOfFiles[i].isDirectory()) {
        Path file = listOfFiles[i].toPath();
        BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);

        String time = attr.lastAccessTime().toString();

        fileList += "<tr><td><img width='15px' alt='**' src='assets\\images\\folder.png'/>&nbsp;"
            + "<button onclick='navigate(this);'>" + listOfFiles[i].getName() + "</button></td><td>" + attr.size() + "</td><td>" 
            + time.replace("T", " ").substring(0, time.indexOf(".")) 
            + "</td></tr>";
    }
}

When I run the project locally, there is no problem. But after deploying my .war file on a server, when running I get a 500 error (null pointer exception) at line:

for (int i = 0; i < listOfFiles.length; i++)

Which tells me that the Folder array has not been initialized with the child folders.

I am assuming that I don't have the same access to these folders on the server as I do when I am running locally.

Any ideas how to access these folders? P.S. The server is running on Unix.

  • I would log "absoultepath" value and see server file systems has folder with exact path. You know what the problem is, so debug and see. – kosa Oct 11 '17 at 19:41

2 Answers2

2

First a small error:

src='assets\\images\\folder.png'

should be

src='assets/images/folder.png'

Then File.listFiles can return null in some cases.

The file names must be case sensitive, the paths separated by /. Seeing the first small error, this might be the case here.

If you deploy the files inside the war, TomCat must be configured to unpack the war zip. Easily checked.

If you upload the files, then the folder and file rights must be okay.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Yes, i went in to the code and checked my file separators, I had them as '\' for windows and not '/' for unix. This solved my issue. Thanks. – Cristian Navarrete Oct 11 '17 at 20:55
1

From https://docs.oracle.com/javase/8/docs/api/java/io/File.html#listFiles--

Returns:

An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

Community
  • 1
  • 1
Nikolay
  • 1,949
  • 18
  • 26