Directory Listing in Java

Hi,
I need to display the directory structure as follows:
Dir Info
Given a directory, traverse them and to find the Size of each individual folders/subfolders in the directory tree, and its depth. Also in a suitable datastruct store the number of files in each dir, number of files by type etc. finally display all the info ie, size and depth of each dir, total number of files in each dir, number of files by type and the overall statistics (total number of files, total number of files by type, total size of the given directory and total number of sub dir etc...
some explanation for depth,the starting directory has a depth 0, 1st level subdirectories have a depth of 1 etc.
Related code will be helpful.
Thanks in advance

Please do not cross post!!!

Similar Messages

  • How to avoid directory listing in java web applications.

    how to avoid directory listing in java web applications.
    That is on typing the url of the application it should not the directory listing. Welcome tag in web.xml doesnot fully solve the problem, since still the images folder etc is still accessible

    I know of two ways.
    If you're using tomcat and have access to the conf directory.
    Edit your $TOMCAT/conf/web.xml. Find your default servlet properties and change
      <servlet>
        <servlet-name>default</servlet-name>
        <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
        <init-param>
          <param-name>debug</param-name>
          <param-value>0</param-value>
        </init-param>
        <init-param>
          <param-name>listings</param-name>
          <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>to  <servlet>
        <servlet-name>default</servlet-name>
        <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
        <init-param>
          <param-name>debug</param-name>
          <param-value>0</param-value>
        </init-param>
        <init-param>
          <param-name>listings</param-name>
          <param-value>false</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>And restart your server. This will affect every directory on the server, and return a 405 directory browsing forbidden error.
    Another way, is to place an index.jsp inside each directory with a simple one line redirect to your applications CONTEXT_PATH.response.sendRedirect("http://yourserver/yourapp/");This will only affect specific directories which contain these index.jsp files.
    Hope this helps

  • Remote  System Directory Listing/Navigation in JTree

    Hi
    I want my Remote System(Linux) directory listing to be available in a JTree. I need some help on implementing the same. Also How do i constantly get the directory structure of the remote system.
    Thanks in Advance

    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    http://en.wikipedia.org/wiki/Model-view-controller
    How you get the data depends on how you access the server. Maybe FTP.

  • How to apply style sheet (.css) in Weblogic directory listing

    Hi,
    We are migrating a directory listing application from Apache to Weblogic.
    Earlier we did this by Apache httpd.conf entry like below :
    <Directory "/opt/apache/httpd-2.1.9/htdocs/Myreportfolder">
    IndexOptions FancyIndexing FoldersFirst NameWidth=* XHTML
    IndexOrderDefault Descending Date
    IndexStyleSheet "/css/style.css"
    </Directory>
    /opt/apache/httpd-2.1.9/htdocs folder has all it's usual resource files.
    We were able to see documents in "Myreportfolder".
    Now we have moved to Weblogic and using virtual directory mapping as below and we are trying to achieve the same thing:
    <?xml version="1.0" encoding="UTF-8" ?>
    - <wls:weblogic-web-app xmlns:wls="http://www.bea.com/ns/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd http://www.bea.com/ns/weblogic/weblogic-web-app http://www.bea.com/ns/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd">
    - <wls:container-descriptor>
    <wls:index-directory-enabled>true</wls:index-directory-enabled>
    <wls:index-directory-sort-by>LAST_MODIFIED</wls:index-directory-sort-by>
    </wls:container-descriptor>
    - <wls:virtual-directory-mapping>
    <wls:local-path>/Myreportfolder</wls:local-path>
    <wls:url-pattern>/*</wls:url-pattern>
    </wls:virtual-directory-mapping>
    <wls:context-root>/getreports</wls:context-root>
    </wls:weblogic-web-app>
    We are able to view the reports but we do not get look-and-feel of Apache like directory listing.
    but we encounter below issues:
    1) File/Folder icons are not visible - we want to use style sheets in http header from the response that is returned from weblogic server
    2) Filename is limited to 29 characters when it is showing
    3) Files are not sortable as Descending order - we sorted using tag <wls:index-directory-sort-by>LAST_MODIFIED</wls:index-directory-sort-by> but the latest file is shown at the last
    We are thinking that Weblogic must be having some configuration like Apache httpd.conf where we can apply style sheets (css ).
    We would appreciate af anyone can provide better insight into the issue.
    or is it possible to extend weblogic.servlet.fileservlet class to serve this purpose.
    Thanks & regards,
    Rabi

    Hi Vikash,
    Check the below links which will you idea on the same.
    Stylesheet for WDA without integrating in SAP Portal
    Apply custom css to WebDynpro application
    Thanks
    KH

  • List() in java.io.file

    Hallo everybody!
    Can someone solve a little problem for me?
    I want to list files and directories in a directory. If one of the files is a dirctory I want to put an "/" to the end of it. I works well if I list the current directory but not if I try to list a path like c:\temp.
    Here is my code :
    public class Lista {
    //int i;
    int i = 0;
    //File Katalog;
    // constructors
    public Lista() {
    usage();
    public Lista(String[] l_files) {
    list_files(l_files);
    // methods
    // method called if 1 argument is passed to main
    private void list_files(String[] lf) {
    // first check if katalog is a file
    File katalog = new File(lf[0]);
    // String c = new String(lf[1]);
    if (katalog.isFile()) {
    System.out.println(katalog + " is a file");
    System.exit(1);
    // check if katalog exists
    if (katalog.exists()) {
    String[] en_lista = katalog.list();
    while (i < en_lista.length) {
    File f = new File(en_lista);
    if (f.isDirectory() == true) {
    //if (f.isFile()) {
    //f.getParent();
    System.out.println(f + "/");
    else {
    System.out.println(f);
    i++;
    else
    System.out.println(katalog + " doesn't exist");
    // method called if no or more than 1 argument are passed to main
    private void usage() {
    System.out.println("\nusage : " + "\njava Lista directory");
    System.exit(0);
    public static void main(String[] args) {
    // depending on the number of arguments passed to main different constructors are called
    if (args.length < 1 || args.length > 2) {
    new Lista();
    else if (args.length == 1) {
    new Lista(args);

    **** example 1 ******
    Here it works as I want it to do
    java Lista . givs the output
    directory/ (the slash mark that it is a directory)
    Lista.class
    Lista.java
    **** example 2 ******
    If I list like below it doesn't work
    java Lista c:\temp givs the output
    directory
    file.txt
    (I want to have the slash in the end of the directory to mark it's a directory but it doesn't)

  • Directory listing for a directory within the webapplication

    Hi,
    I have a the code which does the directory listing of a given directory using its absolute path. eg new File("c:/webapp/tempdir");).
    I want to do the directory listing by giving a path relative to the context path of the webapp like(new File("/temp");)
    When I try to do
    <%
    File f1=new File("/tempDir");
    f1.exists(); --> returns flase
    %>
    tempDir is a directory in my webapplication. How should I reference this? Should I have to use file:// or http://?
    Looking forward for your help
    Thanks in advance

    There is a method in ServletContext: getRealPath.
    http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletContext.html
    It turns a website relative path into a real location on disk.
    // only need this line in a servlet.  "application" is already defined in a jsp
    ServletContext application = getServletConfig().getServletContext();
    String filePath = application.getRealPath("/tempDir");
    File f1 = new File(filePath);Some issues with using this approach:
    If your application is in an unexploded WAR file, then getRealPath() can return null, as there isn't really a location on disk that it relates to.

  • Directory Listing

    Hi All,
    I want to beable to display a directory listing in a JSP page, like filename and if possible size and creation date.
    I found this example :
    http://forum.java.sun.com/thread.jspa?forumID=45&threadID=271208
    But it doesn't do much. This example show how many files it's found but
    doesn't show them.
    Any other examples?
    Thanks!

    All you need is the File class. Check out the api docs (java.io.File), and more specifically the listFiles() method.

  • Directory lister for the web.

    Hi
    Here iam attaching my project code for my particualr aplication
    The source code for a directory lister for the web. You give it
    one or more URLs as arguments and its not displays the formatted results .. can any body will help me
    import java.util.*;
    import java.net.*;
    import java.io.*;
    public class WebList extends abcd.Application
    static final String progName = "WebList";
    public static void main( String[] args )
    (new WebList()).compat( args );
    public int newMain( String[] args )
    int argc = args.length;
    if ( argc == 0 )
    usage();
    return -1;
    for ( int argn = 0; argn < argc; argn++ )
    if ( argc > 1 )
    if ( argn > 0 )
    out.println( "" );
    out.println( args[argn] + ":" );
    list( args[argn] );
    return 0;
    private void usage()
    err.println( "usage: " + progName + " URL ..." );
    void list( String urlStr )
    String base = abcd.Utils.baseUrlStr( urlStr );
    Enumeration as;
    try
    as = new abcd.Spider( urlStr, err );
    catch ( MalformedURLException e )
    err.println( e );
    return;
    while ( as.hasMoreElements() )
    URLConnection uc = as.nextElement();
    if ( uc == null )
    continue;
    URL thisUrl = uc.getURL();
    String thisUrlStr = thisUrl.toExternalForm();
    if ( thisUrlStr.startsWith( base ) )
    thisUrlStr = thisUrlStr.substring( base.length() );
    if ( thisUrlStr.length() == 0 )
    thisUrlStr = ".";
    String mimeType = uc.getContentType();
    int len = uc.getContentLength();
    long mod = uc.getLastModified();
    Date modDate = new Date( mod );
    String modDateStr = abcd.Utils.lsDateStr( modDate );
    out.println(
    abcd.Fmt.fmt( mimeType, 14, abcd.Fmt.LJ ) + " " +
    abcd.Fmt.fmt( len, 8 ) + " " +
    modDateStr + " " + thisUrlStr );
    try
    InputStream in = uc.getInputStream();
    in.close();
    catch ( IOException e ) {}
    }

    Hi,
    It is enumerating the files reachable at or
    below those URLs, i hope it will full fill your application requirements.
    and also in the for loop you have to do pre increment not post increment so it may be the casue for entier your logic ..
    as per my knowledge iam changing the code .. i hope it will work for your application...
    still if you have any querys please post me with details of your projects so that i can help you more..
    here is modified code:
    =================
    import java.util.*;
    import java.net.*;
    import java.io.*;
    public class WebList extends abcd.Application
    static final String progName = "WebList";
    public static void main( String[] args )
    (new WebList()).compat( args );
    public int newMain( String[] args )
    int argc = args.length;
    if ( argc == 0 )
    usage();
    return -1;
    for ( int argn = 0; argn < argc; ++argn )
    if ( argc > 1 )
    if ( argn > 0 )
    out.println( "" );
    out.println( args[argn] + ":" );
    list( args[argn] );
    return 0;
    private void usage()
    err.println( "usage: " + progName + " URL ..." );
    void list( String urlStr )
    String base = abcd.Utils.baseUrlStr( urlStr );
    Enumeration as;
    try
    as = new abcd.Spider( urlStr, err );
    catch ( MalformedURLException e )
    err.println( e );
    return;
    while ( as.hasMoreElements() )
    URLConnection uc = (URLConnection) as.nextElement();
    if ( uc == null )
    continue;
    URL thisUrl = uc.getURL();
    String thisUrlStr = thisUrl.toExternalForm();
    if ( thisUrlStr.startsWith( base ) )
    thisUrlStr = thisUrlStr.substring( base.length() );
    if ( thisUrlStr.length() == 0 )
    thisUrlStr = ".";
    String mimeType = uc.getContentType();
    int len = uc.getContentLength();
    long mod = uc.getLastModified();
    Date modDate = new Date( mod );
    String modDateStr = abcd.Utils.lsDateStr( modDate );
    out.println(
    abcd.Fmt.fmt( mimeType, 14, abcd.Fmt.LJ ) + " " +
    abcd.Fmt.fmt( len, 8 ) + " " +
    modDateStr + " " + thisUrlStr );
    try
    InputStream in = uc.getInputStream();
    in.close();
    catch ( IOException e ) {}
    Regards,
    TirumalaRao.
    Developer Technical support,
    sun MicroSystem, India.

  • Directory monitor in Java, help

    Hey everyone,
    I'm attempting to write a directory monitor in java but I'm stuck. I'm trying to find something in Java that is like FileSystemWatcher in .NET but I don't think java does. From what I read is that you have to continually poll the directory for changes. What I would like to know is that are there any events and/or signals raised when a changes are made so that one could catch and process them? If not, could someone explain how to simply poll the directory for changes?
    Thanks
    Barefoot

    barefootsanders wrote:
    This is exactly what I need to do. Now, i already have been working on the last modified time comparison which is relatively simple. What I was stuck on was finding what was different between the two file lists. Would I have to iterate through the entirety of the list and compare each item to find what was different or is there a more efficient way of doing this?The simplest thing to do would be to use Collection's removeAll method to get the difference between the two. This will show you which files have been added (using newList.removeAll(oldList)) and which have been removed (using oldList.removeAll(newList)).
    A few notes:
    * removeAll modifies the collection on which you call it, so you'll need to make copies.
    * File's equals method docs say: Returns true if and only if the argument is not null and is an abstract pathname that denotes the same file or directory as this abstract pathname. Whether or not two abstract pathnames are equal depends upon the underlying system. On UNIX systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows systems it is not.
    So you'll need to decide if that's good enough, or if you want to implement your own comparison for files. Also, it's not clear from the above how shortcuts or symbolic links are handled--whether the shortcut and the original are considered equal or not.
    * Based on the above, you may get different results with a List vs. a Set, so play around and see which one better suits your needs.
    * I think a directory's mod time only changes if you add or remove or rename files, or explicitly change it, as with the touch command in unix. I don't think modifying the contents of an existing directory cause that directory's mod time to be updated. If you want to know when a file has changed, you'll probably have to poll that file's mod time explicitly.
    In light of the above, I suggest you start by writing a small program that does nothing but poll a directory every, say, 5 or 10 or 30 seconds and print out whether it's changed or not. Then, while that program is running, do various things like add, delete, rename, rename with same letters but different case, etc. and see if the program gives you the results you want. If not, you'll have to tweak it based on your findings.

  • Directory Listing Using Weblogic Server

    Hi all,
    I need to be able to browse few directories via web page using Weblogic as WebServer ( on Linux RedHat 5.0)
    for example the directory to be browsed are:
    /home/oracle/swift
    /home/oracle/payables
    Please let me know how I can achieve this !!
    Thanks
    KS

    maybe it's a bit overkill to use the JCA File Adapter
    http://docs.oracle.com/cd/E21764_01/integration.1111/e10231/adptr_file.htm#BABFGIEJ
    which has a "directory listing" feature
    but I think it's not very recommended to use directly the java.io.File class to perform this operation...
    any other thoughts?

  • How to disable the Directory listing for the whole server or a particular a

    Please let me know how to disable the Directory listing for the whole server or a particular application.
    Thank You

    I want to disable the tab focusing( tab index) for a JTextField objectsLook through the API and find methods with the word "focus" in the method name.
    Also can u tell me about how to change the tab index orders for JTextFields."How to Use the Focus Sub System":
    http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html

  • Overriding Tomcat's directory listing

    I made my own directory listing JSP which includes thumbnails of pictures. Right now I have to copy the file, index.jsp, into every directory to make it the directory listing. How can I stop this?

    It doesn't seem to be working, but I suspect it is a newbie error on my part. Here' s my server.xml (I tried it as shown below, in my apps-project.xml file, and outside the <server> key:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <Server>
        <!-- You can add a "home" attribute to represent the "base" for
             all relative paths. If none is set, the TOMCAT_HOME property
             will be used, and if not set "." will be used.
             webapps/, work/ and log/ will be relative to this ( unless
             set explicitely to absolute paths ).
          -->
        <ContextManager workDir="work" >
    <StaticInterceptor listing="false" />
          <!-- ==================== Global modules ==================== -->
            <LoaderInterceptor11  useApplicationLoader="true" />
            <TrustedLoader />
            <LogSetter name="tc_log" timestamps="true"
                 verbosityLevel="INFORMATION"  />
            <LogEvents enabled="false" />
            <!-- Backward compat: read the Context declarations from server.xml-->
            <ContextXmlReader config="conf/server.xml" />
            <!-- Separated Context -->
            <ContextXmlReader config="conf/apps.xml" />
            <AutoDeploy source="modules" target="modules"
                  redeploy="true" />
            <AutoWebApp dir="modules" host="DEFAULT" trusted="true"/>
            <AutoDeploy source="webapps" target="webapps" />
            <AutoWebApp dir="webapps" host="DEFAULT" />
            <PolicyLoader securityManagerClass="java.lang.SecurityManager"
                    policyFile="conf/tomcat.policy" />
            <SimpleMapper1 />
            <SessionExpirer checkInterval="60" />
            <!-- For development you can use randomClass="java.util.Random" -->
            <SessionIdGenerator randomClass="java.security.SecureRandom"
                                randomFile="/dev/urandom" />
            <!-- ========== context processing modules ========== -->
            <!-- This will be the "default" profile
                 ( all except the "global" modules can be set per context )
              -->
            <LogSetter name="servlet_log"
                 timestamps="true"
                 verbosityLevel = "INFORMATION"
                 path="logs/servlet-${yyyyMMdd}.log"
                 />
            <LogSetter  name="JASPER_LOG"
                 timestamps="true"
                 path="logs/jasper-${yyyyMMdd}.log"
                 verbosityLevel = "INFORMATION"  />
            <WebXmlReader validate="true" />
            <ErrorHandler showDebugInfo="true" />
            <WorkDirSetup cleanWorkDir="false" />
            <Jdk12Interceptor />
            <!-- Non-standard invoker, for backward compat. ( /servlet/* ) -->
            <InvokerInterceptor />
            <!-- you can add javaCompiler="jikes" -->
            <JspInterceptor keepGenerated="true"
                   largeFile="false"
                   useJspServlet="false"
                   />
            <StaticInterceptor listings="true" />
            <ReloadInterceptor fullReload="true" />
            <SimpleSessionStore maxActiveSessions="-1" />
            <AccessInterceptor />
            <CredentialsInterceptor />
            <SimpleRealm  filename="conf/users/global-users.xml" />
           <!-- UnComment the following and comment out the
                above to get a JDBC realm.
                Other options for driverName:
                  driverName="oracle.jdbc.driver.OracleDriver"
                  connectionURL="jdbc:oracle:thin:@ntserver:1521:ORCL"
                  connectionName="scott"
                  connectionPassword="tiger"
                  driverName="org.gjt.mm.mysql.Driver"
                  connectionURL="jdbc:mysql://localhost/authority"
                  connectionName="test"
                  connectionPassword="test"
                "connectionName" and "connectionPassword" are optional.
            -->
            <!--
            <JDBCRealm
                debug="99"
             driverName="sun.jdbc.odbc.JdbcOdbcDriver"
             connectionURL="jdbc:odbc:TOMCAT"
             userTable="users"
                userNameCol="user_name"
                userCredCol="user_pass"
             userRoleTable="user_roles"
                roleNameCol="role_name" />
            -->
            <LoadOnStartupInterceptor />
            <Servlet22Interceptor />
            <!-- Tag pooling support.
                 To enable the reuse of tag handlers as described in
                 the JSP spec, uncomment the following.  If your pages
                 use a lot of custom tags, you should see a nice performance
                 gain.
                 Note that placing the interceptor here will enable
                 Tag pooling for all of the web applicatitions loaded -
                 this may be a bad thing if all tags are not coded to
                 handle reuse. To enable pooling only for specific web
                 applications i.e. Contexts, place the interceptor inside of
                 the Context's definition.
                 To view information about tag usage uncomment the tag
                 LogSetter. Set verbosityLevel to DEBUG to see everytime
                 a tag is obtained and released.
            -->
            <!--
            <LogSetter  name="tag_pool_log" timestamps="true"
                path="logs/tagpool-${yyyyMMdd}.log"
                verbosityLevel="INFORMATION" />
            <TagPoolManagerInterceptor />
            -->
            <!-- Request processing -->
            <DecodeInterceptor />
            <SessionId cookiesFirst="true" noCookies="false" />
            <!-- Automatic config generation
                 Set noRoot="false" if you wish to have Tomcat try to take
                   control of the external web server's root context.
                   Additonal configuration of the external web server may be
                   required for this to be successful.
                 Note: Configuration files are not written as part of the
                   default startup behvior.  Append "jkconf" to the startup
                   command to have Tomcat initialize, write the config files,
                   then exit. This may be done while Tomcat is running.
              -->
            <ApacheConfig noRoot="true" />
            <IISConfig noRoot="true" />
            <NSConfig noRoot="true" />
             <!-- Uncoment for apache-style logs
                  Attributes: logFile, flush, format
            <AccessLogInterceptor/>
              -->
          <!-- ==================== Connectors ==================== -->
           <!-- new http adapter. Attributes:
                   secure - use SSL ( https )
                   keystore, keypass - certs for SSL
                   port
                   reportedname - Server name to send back to browser
                                  by default report Tomcat Web Server ...
                                  set an empty string to avoid sending server header
            -->
            <Http10Connector   port="8080"
                      secure="false"
                      maxThreads="100"
                      maxSpareThreads="50"
                      minSpareThreads="10" />
            <!--
                Uncomment this for SSL support. You _need_ to set up a
                server certificate if you want this to work, and you
                need JSSE. See tomcat-ssl-howto.html for more detailed
                instructions.
                1. Make the JSSE jars available to Tomcat, either by making
                   them an installed extension or by adding them to the
                   Tomcat CLASSPATH.
                2. Do: keytool -genkey -alias tomcat -keyalg RSA
                   RSA is essential to work with Netscape and IIS.
                   Use "changeit" as password. ( or add keypass attribute )
                   You don't need to sign the certificate.
             -->
            <!--
            <Http10Connector  port="8443" secure="true" />
            -->
            <!--
                 JNI connector. It assumes the library is located in
                 TOMCAT_HOME/bin/native/jni_connect.[dll, nlm, so]. or in LD_LIBRARY_PATH.
                 For different paths set "nativeLibrary" parameter.
                 The JniConnector will be self-enable only if JNI mode is detected.
             -->
            <JniConnector />
            <!-- Apache AJP12 support. This is also used to shut down tomcat.
                 Parameter "address" defines network interface this Interceptor
                 "binds" to. Add it if you want to "bind" to just "127.0.0.1".
                 address="127.0.0.1"
                 Parameter "tomcatAuthentication", controls if Tomcat honors
                 ( and uses ) auth done in HTTP Server or not, when true Tomcat does
                 not use in any way auth information provided by the HTTP Server.
                 true is the default.
                 tomcatAuthentication="false"
              -->
            <Ajp12Connector      port="8007" />
            <!-- Apache AJP13 support (mod_jk)
                 Parameter "address" defines network interface this Interceptor
                 "binds" to. Add it if you want to "bind" to just "127.0.0.1".
                 address="127.0.0.1"
                 Parameter "tomcatAuthentication", controls if Tomcat honors
                 ( and uses ) auth done in HTTP Server or not, when true Tomcat does
                 not use in any way auth information provided by the HTTP Server.
                 true is the default.
                 tomcatAuthentication="false"
              -->
            <Ajp13Connector port="8009" />
          <!--
               Context definitions can be placed here ( not recommended ) or
               in separate files. The ContextXmlReader will read all context
               definitions ( you can customize the "base" filename ).
               The default is conf/apps-[name].xml.
               See conf/apps-examples.xml and conf/apps-admin.xml 
           -->
        </ContextManager>
    </Server>

  • Get directory listing or files contained in a folder which is placed on a s

    Hello,
    I want to get the directory listing of a particular folder say 'xyz' which is placed on the server.
    I am using tomcat. I want to use Http to do it. How do it do it.
    Please guide.
    Regards,
    JAVA_student

    JAVA_student ,
    as pointed out file list is (in productional environments) usually turned off for security reasons.
    But I had a similiar requirement to the one you posted. I had a directory with thousands of image files with the name pattern <id>.jpg and the id's stored in a database. Not for every id in the database there existed a file. I wanted to show an image or in case the image file did not exist a default jpg. I could not set the error pages in web.xml to do it.
    So I had to take the id (a parameter in the request to the servlet I wrote for that), had to concat it with the 'virtual' directory name used in the applicationserver for the img directory. Then I had to check the existance of the file and to load it it and display it, if it existed otherwise I had to load and display the default picture.
    The problem is similiar to yours as the problem basically is to map a directory in a web application to a real directory in a filesystem (which works for files and directories.
    The answer is use getRealPath(String) of the ServletContext-object.
    Note: This only allows access to files and directories in the web application.
    e.g.
    http://www.theserver.com/mywebapp/img/ is a folder containing img files. The server does not allow directory listing.
    In a jsp within the application mywebapp you want to show a list of the files in /mywebapp/img/ .
    <HTML>
    <BODY>
    <%
    // in a jsp application gives you access to the context
    String sRealPath = application.getRealPath("/img") ;
    java.io.File fDir = new java.io.File(sRealPath) ;
    java.io.File[] allFiles = fDir.listFiles() ;
    for (int i = 0 ; i < allFiles.length;i++) {
       String sName = allFiles.getName() ;
    %>
    <%=sName%><br>
    <%
    %>
    </BODY>
    </HTML>

  • Very slow network directory listing - but fast data transfer speed once listed?

    Hello,
    I have really tried to sort this myself before opening up to the community, however I have run out of ideas, and hope someone can offer the magic solution I have missed.
    I am currently using the 3.4ghz i7 iMac on a 1GB LAN, running OSX10.7.2 - connecting to a Windows Server 2008 (Running Release 2) over ethernet.
    If i go to a network directory that i haven't recently accessed it can take up to 60 seconds to show the contents of that directory. Once i have accessed that folder, if i come out of it and go back in it will be instant again - but the first time it lists the directory it looks like i have opened an empty folder - which after anything from 10seconds to 1 minute will suddenly show the files that are there.
    Internet connectivity is fast through the network, and file transfers across the LAN are fast. (showing as approx 300mb per second) I can play and edit HD content across the network with no slowdown so I am confident that this issue is not related to the network speed itself, and is more to do with a setting on this mac.
    Symptoms are very similar to this post: https://discussions.apple.com/message/12245148?messageID=12245148&amp%3b#1224514 8 - however i understand that in OSX Lion - SMB was removed - so i cannot find this file to edit.
    I have tried bypassing additional hubs in the network by wiring direct cables to the switch that is connected to the file server, this made no difference.
    I have also tried disconnecting the ethernet cable, and running over wifi. This fixes the listing problem, but when editing HD content over a network drive, this connection is not fast enough to carry the data without interruption (some projects are linked to up to 900gb of hd video content!)
    Using ethernet, I have tried DHCP, DHCP with manual address, and manual mode. All reproduce this problem. i have tried using the windows workgroup, and tried without it.
    I have also followed this suggestion: https://discussions.apple.com/thread/2134936?threadID=2134936&tstart=45 and used OpenDNS. this did not fix the issue.
    For argument sake, I have also just tested a Macbook Pro running Snow Leopard to see if it was OS related. This reproduces the exact same problem, near instant directory listing on the wifi, a long and arduous wait on ethernet.
    I cannot work out why directory listing is instant over wifi, but not over ethernet on 2 different macs, running 2 different versions of OSX. I also do not understand why if the network is having trouble listing the directories - the data transfer speed is 300mbps when i copy files across the wired network from the file server to the mac.
    Does anyone have any other ideas as to what could be the problem here? We are about to start work on a very large project, where the content we are editing is spread out across around 200 different network folders (different shoots captured over the past 2 years). We really don't have the time to wait 60 seconds each time we need to access one of those directories to look for a file, and I am very close to pulling all my hair out!
    I really look forward to hearing from anyone who can offer any insight.

    If you are suspecting that the Windows update had something to do with your LAN going slow, then try the following:
    1.  Look for updates for your clients LAN NIC driver; or
    2.  Un-install the updates.

  • Finding the directory path in java

    I need to check if a file exists or not before an action is taken. I used File class to get the handle of a file and and then used exist() function to check if it is there. But this function needs to full path to that file. I need to find a directory path at runtime as the application is deployed in different environment and wouldn't know the directory path in each environment. Could somebody help me on this. Thanks,

    fBut this function
    needs to full path to that file. I need to find a
    directory path at runtime as the application is
    deployed in different environment and wouldn't know
    the directory path in each environment. Well, that can only you know where this file is on the different platforms. So maybee you can provide it as a user-input, a parameter to the program or be set in a settings-file which the program reads.
    If you want the full path to the current directory where the java program runs, this works:
    File f=...;
    String absPath=f.getAbsolutePath();
    File absPathFile=new File(absPath);Gil

Maybe you are looking for