简体   繁体   中英

Read in all the files in a particular directory displays the file names in a html list in java

package fileBrowser;

import java.io.File;

public class Filewalker {
String str="";
public void walk( String path) {
File root = new File( path );
    File[] list = root.listFiles();
    int numfiles=list.length;
    for (int i=0;i<list.length; i++ ) {

        if ( list[i].isDirectory() ) {
            System.out.print("<li><span>"+list[i].getName()+"</span>\n<ul>");
                if(list[i].listFiles().length==0){
                System.out.println("</ul>\n</li>");
                continue;
            }
            walk( list[i].getAbsolutePath());
        }
        else {
            System.out.println( "<li>"+list[i].getName()+"</li>" );
                    if(i==numfiles-1){
                    System.out.println("</ul>");

                }

        }
    }
}


public static void main(String[] args) {
    Filewalker fw=new Filewalker();
    System.out.println("<ul>");
    fw.walk("C:/test");
    System.out.println("</ul>");

}

}

the nesting of the folders in the ul list is not proper if the the folders have many nested folders when the the method is returning from the inner most folder the closing of the li tag is not happening the output that i am getting is:

<ul>
<li><span>abc</span>
<ul><li><span>ced</span>
<ul><li>New Microsoft Publisher Document - Copy (2).pub</li>
<li>New Microsoft Word Document - Copy (2).docx</li>
<li><span>test</span>
<ul><li><span>inner</span>
<ul><li><span>inner2</span>
<ul><li>New Text Document.txt</li>
</ul>
<li>New Bitmap Image.bmp</li>
</ul>
<li>New Microsoft Publisher Document.pub</li>
<li>New WinRAR ZIP archive.zip</li>
</ul>
<li>New Microsoft Publisher Document - Copy.pub</li>
<li>New Microsoft Publisher Document.pub</li>
<li>New Microsoft Word Document - Copy.docx</li>
<li>New Microsoft Word Document.docx</li>
</ul>
<li>temp1.txt</li>
<li><span>xyz</span>
<ul><li>stud11.txt</li>
<li>temp.txt</li>
</ul>
</ul>
System.out.print("<li><span>"+list[i].getName()+"</span>\n<ul>");
            if(list[i].listFiles().length==0){
            System.out.println("</ul>\n</li>");
            continue;
        }

This code looks like the problem

You open <li> and <ul> but close it only if the directory is empty.

As StanislavL in an answer wrote before, you open tags, but don't close them.

I cannot give you more hints in addition to your code, but would split your listings in 2 functions. Here's my try (tested!) :

public class ListFiles {

    public static void main(String[] args) {
        File root=new File("./../");
        System.out.println("<ul>");
        printDir(root);
        System.out.println("</ul>");
    }

    static void printDir(File dir)
    {
        if(!dir.isDirectory())
            return;

        System.out.println("<li>" + dir.getName() + "</li>");
        System.out.println("<ul>");
        for(File file : dir.listFiles())
        {
            if(file.isFile())
                printFile(file);
            else
                printDir(file);
        }
        System.out.println("</ul>");
    }

    static void printFile(File file)
    {
        if(!file.isFile())
            return;

        System.out.println("<li>" + file.getName() + "</li>");
    }

}

printDir() prints and lists any directory. If a file is found inside the actual directory, printFile() is called to only print one line with the file name. Generally the single println() in printFile() can be moved into printDir() and you won't need an extra function for this, but if you want to print more information to a file, you have a better overview.

Executing this results in:

  • ..
    • ListFiles
      • .classpath
      • .project
      • .settings
        • org.eclipse.jdt.core.prefs
      • bin
        • ListFiles.class
      • src
        • ListFiles.java

Maybe it helps you :-)

You should really consider using the new Files API available in Java 7. It makes your job MUCH easier. Sample code (UNTESTED, but should do the job):

public void printDirectoryToStdout(final Path dirBase)
    throws IOException
{

    System.out.println("<ul>");

    Files.walkFileTree(dirBase, new FileVisitor<Path>()
    {
        @Override
        public FileVisitResult preVisitDirectory(final Path dir,
            final BasicFileAttributes attrs)
            throws IOException
        {
            System.out.printf("<li><span>%s</span>\n<ul>\n", dir.getFileName());
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(final Path file,
            final BasicFileAttributes attrs)
            throws IOException
        {
            System.out.printf("<li>%s</li>\n", file.getFileName());
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(final Path file,
            final IOException exc)
            throws IOException
        {
            throw exc;
        }

        @Override
        public FileVisitResult postVisitDirectory(final Path dir,
            final IOException exc)
            throws IOException
        {
            if (exc != null)
                throw exc;
            System.out.print("\n</ul>\n</li>\n");
            return FileVisitResult.CONTINUE;
        }
    });

    System.out.println("</ul>");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM