Java.io.File exists() problem

I have a web application deployed on a Windows 2000 server and am running Tomcat 4. I want to check for the existence of an image file before displaying it and am trying to use the java.io.File.exists() method. I am using the following code:
String strPicUrl = "/images/thefile.jpg"; //Actual value comes from database
File theFile = new File(application.getRealPath(strPicUrl));
out.print("File Exists: " + theFile.exists() + "<br>");the actual file name in this example is "/images/theFile.jpg", and theFile.exists() always returns true if the file is there, but differs in case. If I try to display the image it doesnt show up under Tomcat because aliasing is turned off by default. I need to find a way to determine if a file exists based on actual case matching. This way if I get a "true" value, the file should be accessible and/or viewable via the JSP engine.
Any ideas how to perform a case sensitive "exists()" regardless of the underlying OS file system?

This looks awesome, but when I tried to implement it without creating a class, I get a method error. Here is the code below:
String theDir = "C:\\Dir\\Subdir\\";
FileFilter theFilter = new FileFilter() {
     private String _theFile = null;
     public boolean accept(File file)
          if (file.isDirectory()) return false;
          String fileName = file.getName();
          if (fileName.endsWith(_theFile)) return true;
          return false;
     public void setTheFile(String theFileParam)  
          _theFile = theFileParam;  
theFilter.setTheFile("theFile.jpg");When I run this I get the following error:
[javac] ...blah error stuff...
[javac] cannot resolve symbol
[javac] symbol : method setTheFile (java.lang.String)
[javac] location: interface java.io.FileFilter
[javac] theFilter.setTheFile("theFile.jpg");
Since I am invoking the FileFilter object directly and not instantiating it in a class, is that causing the error or am I declaring "setTheFile()" wrong?

Similar Messages

  • Java.io.File.exists() timeout?

    Hi. I have some shortcuts on a java app that point to network shares using paths of the type \\servername\share
    Since those shares are in different servers, sometimes one or two are not available and I wanted to have that reflect in the application before the user clicks on them so I've coded it so that the JButton's that point there will an X icon if the share is not available or else, it will have the standard folder icon.
    The code is something like this:
                String endereco = "\\servername\share";
                java.io.File f = new java.io.File(endereco);
                botao.setIcon(menu.icon_verifying);
                if(!f.exists()) {
                    botao.setIcon(menu.icon_error);
                } else {
                    botao.setIcon(icon_success);
                }My problem is that f.exists() takes too long if the share is not available. The way it knows that its not available seems to be to wait for a timeout but the timeout is too long for a regular local area network.
    I can imagine I could do that on another thread and then use a timer to abort it or something but is there a simpler way?
    Thanks.

    your problem is not related to the File class. The File class relies heavily on the local filesystem without knowing that there is some sort of network behind it, so if the local filesystem takes a long time to respond, so will the File class.
    The threading option is a good workaround for your problem. At least it keeps your application responsive.

  • Error when opening itunes : iTunes has stopped working ''A problem caused the program to stop working correctly''. When I repaired damaged files the problem still exists and also after uninstalling and redownloading and installing itunes. I have windows 8

    Error when opening iTunes : iTunes has stopped working '' A problem caused the program to stop working correctly''.
    When I repaired damaged files the problem still exists and also after uninstalling, redownloading and reinstalling iTunes.
    My pc is working with windos 8.
    Is there a solution?

    Hey there Rodney274,
    It sounds like you are getting an error from iTunes when you launch it. I would try the troubleshooting in this article named:
    iTunes for Windows Vista, Windows 7, or Windows 8: Fix unexpected quits or launch issues
    http://support.apple.com/kb/ts1717
    Start with troubleshooting for 3rd party plug ins section, then the rest of the article if needed:
    Start iTunes in Safe Mode
    Open iTunes in Safe Mode to isolate any interference from plug-ins or scripts not manufactured by Apple.
    Hold down Shift–Control while opening iTunes. You should see a dialog that says "iTunes is running in safe mode" before iTunes finishes starting up.
    Click Continue.
    See if the issue you're experiencing persists in Safe Mode.
    If you have the same issue while iTunes is in Safe Mode, proceed to the "Create a new user account" section. If you don't experience the same issue, follow these steps to remove third-party plug-ins.
    Thank you for using Apple Support Communities.
    Take care,
    Sterling

  • Problem in finding java class file

    I am writting an application using servlets , JSP and a simple java classfile. The simple java class file is for connection pool and the name of connection pool class is DBConnectionManager . I am using JavaWebserver2.0 and I have placed this class file in .\JavaWebserver2.0\classes
    I am placing my servlets in .\JavaWebserver2.0\servlets folder. Since I am using wfm package so my servlets are placed in .\JavaWebserver2.0\servlets\wfm .
    The problem is with compiling the servlet placed in wfm folder . I get the following error:-
    TestServlet.java:11:cannot resolve symbol
    symbol: class DBConnectionManager
    location: class wfm.TestServlet
    However when I try to compile this class in servlets folder and remove the package statement from the source file, it compiles and works very fine. I am having lot of confusion as the class DBConnectionManager is in classpath but even then compiler gives error. The same class when placed in servlets folder and package statement is removed works very fine.
    Kindly help.

    Hi,
    Is the DBConnectionManager class declared public?
    Does the TestServlet import the package that contains the DBConnectionManager?
    This is all I can come up with, with the current information.
    Cheers,
    --Arnout                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • -- A file association problem exists, which prevents the file you're trying to download from being associated with the correct application by the operating system using window 7  IE 11

    A file association problem exists, which prevents the file you're trying to download from being associated with the correct application by the operating system
    USING WINDOW 7  IE 11  HOW CAN I FIX???

    Try downloading the offline installers:
    Adobe Reader
    Flash Player for Internet Exporer - ActiveX
    Flash Player for Firefox - NPAPI

  • How to create a UML diagram from a existing .java/.class file?

    I want to create a UML diagram from a existing .java/.class file automatic in JDeveloper. Can I get it? thanks!

    create a new class diagram and then simply drag the java classes from your project onto the diagram area.

  • Problem to include java script file in servlet

    I couldn’t use any functions included in java servlet file using servlet. I made a test in jsp and it work fine but in servlet not.
    Here my code
    out.println("<jsp:include page=\"C:/path/file.js\" flush=\"true\" />");
         or          
         out.println("<script language=\"javascript\" src=\"c:/path/file.js\">");
    Although was no error but using both didn’t let me use any function inside the java script file. As I said using the same command in JSP works fine.
    How I can include the file.js correctly ?

    [email protected] wrote:
    server machineOK, imagine that I am the server and you are the client.
    I have a file "c:/documents and settings/balusc/passwords.txt".
    So now you have the path. Can you tell me the contents of the file?

  • .java.policy file problem

    Is there someone who knows how to reinitialise the java policy file at runtime?
    My signed applet writes a policy file to the users home directory, but that file is only used after closing the browser and surfing back to our page. It should immediatly use that new file.
    Someone who got some experience with that...?
    Regards

    And is it true that if you use a Thawte or verisign certificate, you will not have to change the .java.policy file?

  • File open/exists problems under Mavericks

    If I try to open a file under Mavericks, it says Path is not a valid path even if the files exists for real.
    I even tried app.project.file.exists for an opened project, and it return false.
    Anybody have an idea ?
    CS6, OSX 10.9
    By the way my project file is on the desktop, i also tried putting it in Documents, Downloads,etc.. but didn't work either... However it is working on an external drive...

    Wow, ahahah.
    Found the bug source. A big OSX security flaw in my opinion. As the file was on the desktop, the path was Users/Me/Desktop/... However, I had a network connection to my pc, and the link was to my user account, Users/me/... So OSX was not trying to open its own /Users/ path but my PC folder... Somebody could fool the system, by creating a volume called /Users/... with some fake duplicate files, and someone could try to open something on his drive, but in fact it would load the evil Users volume.
    I don't understand how this could be possible. I never understood how bad the OSX network volumes system was that bad, but never tought it would be so crappy.

  • Problem opening java code file

    I downloaded some code for a slide out menu and am unable to open the file after unzipping it. Yes, I am a beginner and know near to nothing about java.
    Here's the message that came up:
    Script: C:\Documents and Setting\etc...etc
    Documents\passion\ssm6_6\ssmitmes.js
    Line: 1
    Char:1
    Error: Syntax error
    Code: 800A03EA
    Source: Microsoft JScript compilation error
    So what's with that? I know it's my computer but I don't know where to go for answers so I thought here'd be a good start.
    Any hints are greatly appreciated, thanks ya'll!!

    There is some errror in The ssmitmes.js java script file. Just try to edit it and clear it.

  • UNC paths and java.io.file in Oracle

    Hi,
    I'm just getting to grips with using some basic java in the database. I'm using 8.1.7 on W2K.
    I'm trying to test for the existance of a file on a separate w2k domain:
    import java.io.File;
    public class JFileExists {
    public static int fileexists (String fileName) {
    File myFile = new File (fileName);
    boolean retval = myFile.exists();
    if (retval) return 1; else return 0;
    public static void main (String args[]) {
    System.out.println (
    fileexists (args[0])
    grant javasyspriv to mp;
    function jfn_file_exists (file_in IN VARCHAR2) RETURN number
    AS LANGUAGE JAVA NAME 'JFileExists.fileexists (java.lang.String) return int';
    From the command prompt all is well:
    E:\java>"c:\oracle\ora81\Apache\jdk\bin\java.exe" JFileExists i:\test.txt
    1
    E:\java>"c:\oracle\ora81\Apache\jdk\bin\java.exe" JFileExists \\mpweb1\image\test.txt
    1
    But when loaded into oracle its returning false with the UNC path. (but is ok with a mapped drive to the same path)
    SQL> declare
    2 begin
    3 pa_main.pr_print(to_char(pa_main.jfn_file_exists('I:\test.txt')));
    4 pa_main.pr_print(to_char(pa_main.jfn_file_exists('\\mpweb1\image\test.txt')));
    5 end;
    6 /
    1
    0
    PL/SQL procedure successfully completed.
    The oracleservicesid and listener are starting under a user called oracle_user which is a member
    of the admins and domain admins group.
    mpweb1 is on a separate domain to the database server mpdb1 but it also has a user called oracle_user with the same password.
    oracle_user has full access to the share in question.
    Am I missing something? I was trying to keep the database server and web server on different domains for better security
    - but would things be easier if they were on the same domain?
    Any help much appreciated for this java newbi!
    Thanks,
    Simon.
    null

    I am also having problems with UNC paths. But I cannot access the location even if it is mapped as a drive. In JDK VJM I do not have a problem, but in Oracle it says the file cannot be found and say permission denied. I will try to change the user that starts the database and see if that helps.
    null

  • NFS File Access problem

    Hello,
    I am having problems trying to "tail" an existing file.
    When the file is being written into, I can tail it without any problem.
    The problem rises when the file is already complete, and I try to open it.
    I tried to make a small demo program but for some reason I am unable to get the demo program to give the same behaviour.
    Below is the class in which it all goes wrong.
    I basically opens the file usring RandomAccessfile.
    when I try to retrieve the length of the file a bit further, my ascii file I am viewing already changed to .nfs01231353434 something.
    But all gets displayed ok.
    When I then close the text pane in which this tail class is logging, the file itself is deleted.
    As this has something to do with NFS here is the setup :
    The java jar file is located on a remote solaris disk, so is the ASCII file I am trying to view.
    The local machine where I am running my application is Red Hat Linux 3.2.3-52.
    Apologies if this information is kinda vague but as I am unable to supply a demo program, I dont know else how to explain my problem.
    The class that does the "tailing"
    package com.alcatel.tamtam.main;
    import java.io.*;
    import java.util.*;
    public class Usr_LogFileTrailer extends Thread
       * How frequently to check for file changes; defaults to 5 seconds
      private long sampleInterval = 5000;
       * Number of lines in a row we output, otherwise problems with large files
       private int lineBuffer = 250;
       * The log file to tail
      private File logfile;
       * Defines whether the log file tailer should include the entire contents
       * of the exising log file or tail from the end of the file when the tailer starts
      private boolean startAtBeginning = false;
       * Is the tailer currently tailing ?
      private boolean tailing = false;
       * Is the thread suspended or not ?
      private boolean threadSuspended = true;
       * File pointer where thread last logged a line
      private long filePointer = 0;
       * Set of listeners
      private Set listeners = new HashSet();
       * Creates a new log file tailer that tails an existing file and checks the file for
       * updates every 5000ms
      public Usr_LogFileTrailer( File file )
        this.logfile = file;
       * Creates a new log file tailer
       * @param file         The file to tail
       * @param sampleInterval    How often to check for updates to the log file (default = 5000ms)
       * @param startAtBeginning   Should the tailer simply tail or should it process the entire
       *               file and continue tailing (true) or simply start tailing from the
       *               end of the file
      public Usr_LogFileTrailer( File file, long sampleInterval, boolean startAtBeginning )
        this.logfile = file;
        this.sampleInterval = sampleInterval;
        setPriority(Thread.MIN_PRIORITY);
      public void addLogFileTailerListener( Usr_LogFileTrailerListener l )
        this.listeners.add( l );
      public void removeLogFileTailerListener( Usr_LogFileTrailerListener l )
        this.listeners.remove( l );
       *  Methods to trigger our event listeners
      protected void fireNewLogFileLine( String line )
        for( Iterator i=this.listeners.iterator(); i.hasNext(); )
          Usr_LogFileTrailerListener l = ( Usr_LogFileTrailerListener )i.next();
          l.newLogFileLine( line );
      public void stopTailing()
        this.tailing = false;
      public void restart()
        filePointer = 0;
      public synchronized void setSuspended(boolean threadSuspended)
        this.threadSuspended = threadSuspended;
        if ( ! threadSuspended ) notify();
      public void run()
        try
          while ( ! logfile.exists() )
            synchronized(this)
              while ( threadSuspended ) wait();
            Thread.currentThread().sleep(1000);
            File parentDir = logfile.getParentFile();
            if ( parentDir.exists() && parentDir.isDirectory() )
              File[] parentFiles = parentDir.listFiles();
              for ( File parentFile : parentFiles )
                if ( parentFile.getName().equals(logfile.getName()) ||
                     parentFile.getName().startsWith(logfile.getName() + "_child") )
                  logfile = parentFile;
                  break;
        catch(InterruptedException iEx)
          iEx.printStackTrace();
        // Determine start point
        if( this.startAtBeginning )
          filePointer = 0;
        try
          // Start tailing
          this.tailing = true;
          RandomAccessFile file = new RandomAccessFile( logfile, "r" );
          while( this.tailing )
            synchronized(this)
              while ( threadSuspended ) wait();
            try
              // Compare the length of the file to the file pointer
    //          long fileLength = 0;
              //long fileLength = file.length();
              long fileLength = this.logfile.length();
              if( fileLength < filePointer )
                // Log file must have been rotated or deleted;
                // reopen the file and reset the file pointer
                file = new RandomAccessFile( logfile, "r" );
                filePointer = 0;
              if( fileLength > filePointer )
                // There is data to read
                file.seek( filePointer );
                String line = file.readLine();
                int lineCount = 0;
    //            this.fireBlockTextPane();
                while( line != null && lineCount < lineBuffer)
                  this.fireNewLogFileLine( line );
                  line = file.readLine();
                  lineCount++;
                filePointer = file.getFilePointer();
                this.fireFlushLogging();
    //            this.fireNewTextPaneUpdate();
              // Sleep for the specified interval
              sleep( this.sampleInterval );
            catch( Exception e )
                e.printStackTrace();
          // Close the file that we are tailing
          file.close();
        catch( Exception e )
          e.printStackTrace();
      }

    Hi,
    Below is my NFS mount statement on database server and application server. BTW, the directory DocOutput has permission of 777.
    fstab on the Database Server
    appserver:/database/oracle/app/prod/DocOutput /DocOutput nfs rw,hard,retry=20 0 0
    exports file in the Application Server
    /database/oracle/app/prod/DocOutput -anon=105,rw=dbserver,access=dbserver

  • File.exists()  returs false even the file is present in the specified path

    Hi,
    When i try to run the following program which checks whether the file exists in the given path or not
    public class FileCheck {
    public static void main(String[] a){
    String str = a[0];
    File f = new File(str);
    if(f.exists())
    System.out.println("File Exists ");
              else
         System.out.println("File does not Exists ");
    So on solaris 10(korean) we have file named in korean language under "usr" directory. When i try to run the above program on solaris 10(Korean) using the default jre (1.5)with the parameter "/usr/file name in korean language" .The output of the program is "File Exists"
    And when i run the same class file using the jre (1.6) which is installed in our application which is an english version with the same parameter ""/usr/file name in korean language"
    The output of the program is "File does not exists".
    And this problem is only with the files which contain the name in korean language.
    So do we need to set any properties for the jre in our application to work for files which are named in korean language. Any help will be highly appreciated.
    Thanks,
    GPK
    Edited by: gpk_04 on Nov 11, 2008 1:46 PM
    Edited by: gpk_04 on Nov 11, 2008 1:57 PM

    My guess is that Java 5 and 6 are picking up the file system encoding differently. As a consequence, the JVM is either:
    1. reading and converting your command line argument incorrectly, or
    2. reading and converting the file name from the file system incorrectly.
    Write a quicky, short app that prints out the file encoding of your host. Run this under 5 and then 6. Do you see different outputs?

  • Trying to write data to a text file using java.io.File

    I am trying to create a text file and write data to it by using java.io.File and . I am using JDeveloper 10.1.3.2.0. When I try run the program I get a java.lang.NullPointerException error. Here is the snippet of code that I believe is calling the class that's causing the problem:
    String fpath = "/test.html";
    FileOutputStream out = new FileOutputStream(fpath);
    PrintStream pout = new PrintStream(out);
    Do I need to add additional locations for source files or am I doing something wrong? Any suggestions would be appreciated.
    Thank you.

    Hi dhartle,
    May be that can help:
    * Class assuming handling logs and connections to the Oracle database
    * @author Fabre tristan
    * @version 1.0 03/12/07
    public class Log {
        private String fileName;
         * Constructor for the log
        public Log(String name) {
            fileName = name;
         * Write a new line into a log from the line passed as parameter and the system date
         * @param   line    The line to write into the log
        public void lineWriter(String line) {
            try {
                FileWriter f = new FileWriter(fileName, true);
                BufferedWriter bf = new BufferedWriter(f);
                Calendar c = Calendar.getInstance();
                Date now = c.getTime();
                String dateLog =
                    DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM,
                                                   Locale.FRANCE).format(now);
                bf.write("[" + dateLog + "] :" + line);
                bf.newLine();
                bf.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
         * Write a new line into a log from the line passed as parameter,
         * an header and the system date
         * @param   header  The header to write into the log
         * @param   info    The line to write into the log
        public void lineWriter(String header, String info) {
            lineWriter(header + " > " + info);
         * Write a new long number as line into a log from the line 
         * passed as parameter, an header and the system date
         * @param   header  The header to write into the log
         * @param   info    The line to write into the log
        public void lineWriter(String header, Long info) {
            lineWriter(header + " > " + info);
         * Enable to create folders needed to correspond with the path proposed
         * @param   location    The path into which writing the log
         * @param   name        The name for the new log
         * @return  Log         Return a new log corresponding to the proposed location
        public static Log myLogCreation(String location, String name) {
            boolean exists = (new File(location)).exists();
            if (!exists) {
                (new File(location)).mkdirs();
            Log myLog = new Log(location + name);
            return myLog;
         * Enable to create the connection to the DB
         * @return  Connection  Return a new connection to the Oracle database
        public static Connection oracleConnectionCreation() throws Exception {
            // Register the Oracle JDBC driver
            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
            //connecting to the DB
            Connection conn =
                DriverManager.getConnection("jdbc:oracle:thin:@myComputerIP:1521:myDB","user", "password");
            return conn;
         * This main is used for testing purposes
        public static void main(String[] args) {
            Log myLog =
                Log.myLogCreation("c:/Migration Logs/", "Test_LinksToMethod.log");
            String directory = "E:\\Blob\\Enalapril_LC-MS%MS_MS%MS_Solid Phase Extraction_Plasma_Enalaprilat_ERROR_BLOB_test";
            myLog.lineWriter(directory);
            System.out.println(directory);
    [pre]
    This class contained some other functions i've deleted, but i think it still works.
    That enables to create a log (.txt file) that you can fill line by line.
    Each line start by the current system date. This class was used in swing application, but could work in a web app.
    Regards,
    Tif                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Java.io.File and uppercase/lowercase

    Hello,
    I am running into a weird problem with java.io.File on a Windows system. My program needs to validate a path the user entered. Sometimes, the path will contain a directory name that should be uppercase, but which the user entered in lowercase instead, and the <File>.exists() returns true anyways. I know on Windows, on the command line, directory and file names are not case-sensitive, which is probably why it was done that way. But this is causing problems because once the path is (supposedly) validated, it is handed to a Unix program (case-sensitive), and if it's not really valid there, the user has no way of correcting it. Whereas if it were found as invalid in the Java program, I could pop up an error, and the user could correct it.
    The bottom line is, is there a way of telling a File object to return false if the path name is not EXACTLY identical, on Windows? Or would I have to check the path myself, without relying on File?
    Thanks in advance,
    J-S

    In this case, this is not acceptable, since the files or directories on disk can be in any case. I just need the entered case to be exactly the same as the files.
    In other terms, I need File.exists() to return false if the case does not match. I would think there is a way to do this, since internally, the function checks if the operating system is Windows or Unix before doing the comparison, and acts differently in each case...
    From http://java.sun.com/j2se/1.3/docs/api/java/io/File.html (see equals or compareTo method) :
    "On UNIX systems, alphabetic case is significant in comparing pathnames; on Win32 systems it is not."
    I would like to force the Unix way of doing.

Maybe you are looking for

  • I am trying to setup kvm. Am I on the right track?

    I am trying to  set up kvm and am a bit confused (probably by old information) lscpu Virtualization: AMD-V L1d cache: 16K L1i cache: 64K L2 cache: 2048K L3 cache: 8192K NUMA node0 CPU(s): 0-5 grep -E "(vmx|svm|0xc0f)" --color=always /proc/cpuinfo Wor

  • Firefox won't open; I get the msg. "Cannot open file or DLL C:\WINDOWS\system32\USP10.dll - what's up?

    I've tried uninstalling Firefox, re-downloading it (various versions and sites), and re-installing; I just get the same reference to "USP10.dll" in directory C:\WINDOWS\ system32 ... so wha' happen? I don't think I did anything (install or whatever)

  • How can I uninstall Magic TrackPad update

    Yyyyyyikes!!! First of all I'm totally fed up with these two words: "magical" and "revolutionary". Enough already. Secondly I can't understand why apple is trying so hard to become americas next top microsoft. Ok. The magically padish tracsies update

  • What is a keychain and do i need it?

    I have recently forgotten my login password. I got my computer reboted and it is ok now but Keychain access required tabs keep popping up and when i enter my new password it does not recognise it. It is really irritating and i dont know what to...

  • Run automatically FLVPlayer

    Hi I'm a FLVPlayer I want to run automatically after being executed. But now I do not know how to change the code. Class code is as follows: package Classes import flash.display.MovieClip; import flash.events.Event; import flash.events.MouseEvent; im