File.exists() - new filename

Hi all,
I'm looking for a method which creates a new fileName,
if a file in a Directory already exists.
if the oldfileName is "file1.txt"
the new Filename should be
"file2.txt"
String newFilename = "";
if (file.exists())
newFilename  = createNewFilename(theFile.getName());
}is there any simple solution to generate automatically
new fileNames.
Thanks for your help.
Frank

You could create a file name create function based on this prinicpal.
public String (String oldName){
   int oldLength = oldName.length();
   char[] oldArray = oldName.toCharArray();
   int fileNum = Integer.parseInt(new String(oldArray[oldLength - 1]);
   fileNum++;
   String newName = oldName.subString(0,oldLength-2) + fileNum;
   return newName;

Similar Messages

  • File exist to check for any file, not just a specific filename

    How can I implement a check to see if any file exists in a certain directory. I don't know the filename beforehand, only the directory.
    Can I still use the FILE EXISTS activity or do I need to write something different.
    Thanks,
    Guido

    Hi guidonlm
    You can use USER DEFINED activity or FILE EXISTS activity. With file exists you must get file name before (file name can be hard coded or passed as variable). With user defined activity you can make your own shell script and check anything that you need (in this case you must enable property in file $ORACLE_HOME/owb/bin/admin/Runtime.properties property.RuntimePlatform.0.NativeExecution.Shell.security_constraint = NATIVE_JAVA
    Regards

  • ERR:10003 Unexpected data store file exists for new data store

    Our TimesTen application crashes and then it can not connect TimesTen datastore, and then we use ttIsql and get error "10003 Unexpected data store file exists for new data store".So we must rebuild the DataStore.
    I guess the application damages the datastore because we use "direct-linked" mode. Is it true?
    Should I use "Client-Server" mode if our data is very important?
    thx!

    Your question raises several important discussion points:
    It is possible (though very unlikely in practice) for a C or C++ program operating in direct mode to damage the contents of the datastore e.g. by writing through an invalid memory pointer. In the 11+ years that TimesTen has existed as a commercial product we have so far never seen any support case where this was diagnosed as the cause of a problem. However, it is definitely a theoretical possibility and rigorous program testing and use of tools such as Purify is strongly recommended when developing in C or C++ in direct mode. Java programs running in direct mode are completely 'safe' unless they invoke non-Java code via JNI when a similar risk is present.
    The reality is that most customers who use TimesTen in very high performance mission critical applications use mainly direct mode...
    Note also that an application crashing should not cause any damage or corruption to a datastore, even if it is using direct mode, as Times%Ten contains explicit mechanisms to guard against this.
    Your specific problem (error 10003) is nothing to do with the datastore being damaged. This error reflects a discrepancy between the instance main daemon's metedata about all the datastores that it is managing and the reality. This error occurs when the main daemon does not know about a datastore and yet when it comes to connect to (and hence create) the datastore it finds that checkpoint or log files already exist. The main daemon's metadata is managed solely by the main daemon and is completely separate from the datastore and datastore files (the default location is <tt_instance_install_directory>/info, though you can change this at install time). The ususal cause of this is that someone has been manually manipulating files within that directory (which of course you should never do) and has removed or renamed the .DBI file corresponding to the datastore.
    This error should never arise under normal circumstances and certainly not just because some application has crashed.
    Rather than simply switching to the (much slower) client/server mode I think we should try and understand why this error is occurring. Could you please post the following:
    1. Output of ttVersion command
    and then we can take it from there.
    Thanks, Chris

  • Why is my powerpoint not working 10.9? i can't play my existing file and new files that i work..? how to fix that one..? pls help..!

    why is my powerpoint not working 10.9? i can't play my existing file and new files that i work..? how to fix that one..? pls help..!

    R Cubss,
    You might want to read down this thread. There are a lot of tips-n-tricks, and maybe one will be right for you.
    http://www.adobeforums.com/webx/.59b6565c/43
    Good luck,
    Hunt

  • 1003 error:unexpected data store file exists for new data store

    dear chris
    when we use timesten, what happened cause the error 1003, I don't know what cause it happen. it works well before. but it happened today twice.
    anyone know the reason ?? Any help is appreciated!
    Thanks

    The TimesTen daemon maintains a 'catalog' containing information about datastores that it is managing. From the daemon's perspective, a datastroe is uniquely identified by the pathname for the checkpoint files (the value of the DataStore attribute in a DSN definition). The daemon knows nothing about DSNs or ODBC.INI files...
    A datastore is physically created, and hence registered with the instance daemon, the first time something connects to it specifying the ODBC/connection attribute AutoCreate=1 (which is the default value). From that point, the datastore has a physical existence (checkpoint and log files exist on disk), is known to the daemon and hence will appear in the output of the ttStatus command.
    If at the time you connect to a datastore with AutoCreate=1 and the daemon has no record of the datastore it will try and create it. If it finds that the checkpoint files already exist in the specified location on disk then this is 'unexpected' (since the datastore should not exist yet) and error 1003 results.
    Seems like you have somehow got some checkpoint files existing that the daemon does not know about. You have made some kind of mistake somewhere I guess; maybe you copied files around inadvertently?
    Chris

  • Reading file from a folder : File dir = new File(URL+aFile_to_add);

    Hi,
    Trying to read files from a dir on my site using a JSP and bean. I've tried nearly every option for the filepath I can think of and it doesn't seem to be finding the file...
    Here's the bit:
    String URL = "images\\wedding_photos\\";
    File dir = new File(URL+aFile_to_add);
    String[] files = dir.list();
    It's working locally, but I obviously had to change the path from c://... to the above.
    The full code is listed below in the addWedding Method
    The method removes the .jpg from the file name and then writes the new file name to a database
    Thanks for any insight.
    Regards
    Jim
    public String addWedding(String aFile_to_add)
    String feedback = "unset in scrubWedding";
    try
    String URL = "images\\wedding_photos\\";
    Class.forName("org.gjt.mm.mysql.Driver");
    java.sql.Connection connection = java.sql.DriverManager.getConnection("jdbc:mysql://localhost/rhwedd2_shop?user=**********&password=*******");
    java.sql.Statement statement = connection.createStatement();
    File dir = new File(URL+aFile_to_add);
    String[] files = dir.list();
    if (files == null)
    feedback = "Sorry, couldn't find the file "+aFile_to_add+"...no files have been added.";
    else
    for (int i=0; i<files.length; i++)
    // Get filename of file or directory
    String filename = files;
    String no_extension;
    //convert string array element into a char array
    char [] charsfilename = filename.toCharArray();
    int newlength = charsfilename.length -4;
    no_extension = String.valueOf(charsfilename,0,newlength);
    filesAdded = filesAdded+", "+no_extension;
    // Show the new file names in stack trace without extension
    //System.out.println("String no_extension " + no_extension );
    statement.executeUpdate("INSERT INTO items VALUES ('"+no_extension+"',5,'"+aFile_to_add+"')");
    // write to table with item_id and weddingid
    feedback = "The following files have been added..."+filesAdded;
    if (statement != null )
    statement.close();
    if ( connection != null )
    connection.close();
    catch(Exception e)
    feedback = "Into the catch";
    e.printStackTrace(System.err) ;
    return feedback;
    }//end addWedding

    String URL = "images\\wedding_photos\\";
    File dir = new File(URL+aFile_to_add); ok, ok, I'll answer...
    1) What gives you the impression that the relative directory "images\\..." exists (or, in other words, what makes you think your current directory is the parent of "images"?

  • FTP-Sender Adapter ignores files with "known filenames"

    Hello experts,
    the scenario is FTP -> XI -> IDOC and we have problems with the polling of the files. In communication channel monitoring everything is working fine, but in the FTP folder some files are ignored, although the communication channel is set up for all *.txt-files.
    My question is, is it possible that the FTP sender adapter ignores files, if it already has processed a file with the same filename? After renaming the files they all were picked up and archived into another folder. How can I configure the communication channel to pick up ALL *.txt-files in the out-folder?
    Best regards
    David

    Hi David,
    What I have observed is, XI always reads files in a certain order (possibly alphabetical or reverse alphabetical). If it finds a file in the source directory that already exists in the archive directory, it will not attempt to read/process the next file (even if the next filename is completely new).
    So, if any of the files in the source directory exist in the archive directory, there is a possibility that certain files may get processed and certain wont.
    Make sure that none of the files that you put in source directory exist in the archive directory (i.e. all the files are new) and see the output. Let me know if this helps.
    PS: I used FTP protocol
    Regards,
    Riyaz

  • 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?

  • File.exists() is not accurate on smb2 network share (use WatchService?)

    Hi,
    According to this document: SMB2 Client Redirector Caches Explained File.exists() is not accurate on a smb2 network share. I am not able to change any register settings, so I want to deal with it. According to the document there is an API to get the notifications from the file system. I assumed that the WatchService is the Java implementation of this API. Am I correct?
    I started with the WatchDir example from the jdk samples and stripped it a bit. I only need to know when a file is created and delete (I don't care about file modifications). For testing I have added new File.exists() when a new event has been triggered. I also start a separated Thread which test the file existence also. When I don't start this separated thread the file exists returns true immediately. When the extra thread is started it is not accurate any more. I need a more accurate file.exists check in the whole application and all running threads.
    The output for my test case is this:
    FileExistsThread: subdir\test.txt == false
    watch registered for dir: subdir\
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    WatchDir event: ENTRY_CREATE: test.txt
    WatchDir: subdir\test.txt exists == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == true
    FileExistsThread: subdir\test.txt == true
    FileExistsThread: subdir\test.txt == true
    FileExistsThread: subdir\test.txt == true
    As you can see the file test.txt  is created on line 9. The FileExistsThread have seen it on line 20, (at least 10 x 300 ms later).
    For testing I have used 2 Windows 7 pc's (with smb2 enabled which is default). The working directory must be on the remote pc and the file test.txt must be created (or copied from another folder) on the remote pc (not using the network drive, but on the pc itself).
    Here is my test code:
    package nl.test.main;
    import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
    import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
    import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
    import java.io.File;
    import java.io.IOException;
    import java.nio.file.ClosedWatchServiceException;
    import java.nio.file.FileSystems;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.WatchEvent;
    import java.nio.file.WatchKey;
    import java.nio.file.WatchService;
    public class WatchDir
      private final WatchService _watcher;
      private final String _dir;
      public WatchDir( String dir ) throws IOException
        _dir = dir;
        _watcher = FileSystems.getDefault().newWatchService();
        Paths.get( dir ).register( _watcher, ENTRY_CREATE, ENTRY_DELETE );
        System.out.println( "watch registered for dir: " + dir );
      public void run()
        try
          while ( true )
            WatchKey key = _watcher.take();
            for ( WatchEvent<?> event : key.pollEvents() )
              WatchEvent.Kind<?> kind = event.kind();
              if ( kind == OVERFLOW )
                continue;
              @SuppressWarnings( "unchecked" )
              WatchEvent<Path> ev = (WatchEvent<Path>)event;
              Path fileName = ev.context();
              System.out.println( "WatchDir event: " + kind.name() + ": " + fileName );
              if ( kind == ENTRY_CREATE )
                String realPath = _dir + fileName;
                System.out.println( "WatchDir: " + realPath + " exists == " + new File( realPath ).exists() );
            key.reset();
        catch ( ClosedWatchServiceException x )
          return;
        catch ( InterruptedException ex )
          return;
      public static void main( String[] args )
        Thread t = new Thread( new Runnable()
          @Override
          public void run()
            try
              while ( true )
                String filename = "subdir\\test.txt";
                boolean fileExists = new File( filename ).exists();
                System.err.println( "FileExistsThread: " + filename + " == " + fileExists );
                Thread.sleep( 300 );
            catch ( InterruptedException e )
              e.printStackTrace();
              return;
        t.start();
        try
          new WatchDir( "subdir\\" ).run();
        catch ( IOException e )
          e.printStackTrace();
    Any idea's?
    Thanks,
    Olaf

    If you donot have access to note 45172.1 as specified by Laurent Schneider.
    Snippet from note
    a. Mapped Drive : To use a mapped drive, the user that the service starts as
    must have setup a drive to match UTL_FILE_DIR and be logged onto the server
    when UTL_FILE is in use.
    b. Universal Naming Convention : UNC is preferable to Mapped Drives because
    it does not require anyone to be logged on and UTL_FILE_DIR should be set to
    a name in the form :
    \\\<machine name>\<share name>\<path>
    or
    "\\<machine name>\<share name>\<path>"

  • File.exists() returns false for existing file, help :)

    Hi all,
    I'm having the STRANGEST behavior... I'm working on a simple DNS management system, and before I overwrite a zone file, I want to check if it exists... but exists() is returning false even when the file exists.
    Here is my code snippet:
    finest( "Checking the existance of "+filename ) ;
    File zoneFile = new File( filename ) ;
    if ( zoneFile.exists() ) {
        finest( "Zone File "+zoneFile+" already exists." ) ;
        throw( new ZoneFileExistsException( fqdn ) ) ;
    else {
        finest( "Creating Zone File "+zoneFile ) ;
        ...It's producing this in the log (I cut off the timestamp parts):
    Checking the existance of /opt/DNS/db.testingbutler222.com
    Creating Zone File /opt/DNS/db.testingbutler222.com
    but...
    # ls -l /opt/DNS/db.testingbutler222.com
    -rw-r--r-- 1 root other 733 Aug 27 19:23 /opt/DNS/db.testingbutler222.com
    So... as you can see, the file CLEARLY exists... what the heck am I doing wrong or misunderstanding? This can't really be a bug in File, can it?
    Kenny Smith

    Hi,
    Thanks for your response, but as I showed in my first post, I'm using absolute paths. My log file contains this:
    Checking the existance of /opt/DNS/db.testbutler222.com...
    Existance of /opt/DNS/db.testbutler222.com=false
    # ls -l /opt/DNS/db.testbutler222.com
    -rw-r--r-- 1 root other 695 Aug 29 12:17 /opt/DNS/db.testbutler222.com
    I don't understand what is happening... I wrote a separate class that just tests the existance of a file, and that one is reporting the existance correctly.... (the source code is found in the second post above) I don't understand why my servlet code can see the file.
    I have jakarta-tomcat running as root, and the file I'm checking was created by the same servlet. I've double checked permissions and such, just to make sure it wasn't that.. but it's still not working.
    I even added code to create a FileReader from the file, that way if it throws a FileNotFoundException, I would know the file doesn't exist... and even though the file does exist, it throws the exception. :(
    Kenny

  • File.exists() and accent on unix

    Hi,
    I made a main which test if a file exists.
    I created files "toto" and "tété" on windows.
    On windows the two files are seen.
    I transfered them on a redhat.
    The file "toto" is seen but "tété" is not.
    Here is the code :
    public static void main(String[] args) {
            String filename = "/home/user/test/" + args[0];
            System.out.println(new File(filename).exists());
        }I tried to put the name of the file but it was not seen.
    public static void main(String[] args) {
            String filename = "/home/user/test/tété";
            System.out.println(new File(filename).exists());
        }If someone could help me it would be great.
    Thanks.

    can you try
         public static void main(String[] args) {
              File file = new File("/home/user/test/");
              File [] files = file.listFiles();
              for(File f : files){
                   System.out.println(f.getName());
         }if this displays the both file name, then problem with your locale setting of RedHat

  • How to list files existing in a folder ??

    hello
    I want to lis all files that are existing in a folder
    MaApp\myFolder\
    note: myApplication is as executeable Jar file
    I do somthing like that
    File []fileList = (new File(this.getClass().getResource("/MyFolder/").getPath())).listFiles();
        for(int i=0; i < fileList.length; i++){
            String srcName = fileList.getName();
    System.out.println("Filename: "+srcName);
    // but java.lang.NullPointerException will be thrown
    what is to do ????
    thanks

    that is not what I ned
    so.
    Mypp contain mor folders
    myApp/Foder1
    myApp/Folder2
    myApp/Folder3/
    in Folder3 are more files file1.txt, file2.txt,file3.txt,...
    tol list the files wich exist in Folder3
      File []fileList = (new File("Folder3\\")).listFiles();
        for(int i=0; i < fileList.length; i++){
       }this works fine
    but wenn I create an executeable jar of myApp
    I becom an NullPointerException
    becaus there is problem with the path new File("Folder3\\")
    what I want how to let jar to know the path of hiles which are in Folder3
    thanks

  • Best way to see if a URL to filesystem file exists?

    What's the best way to test if a file (specified by a URL) exists? I know if I had a file object, I could just do: new File( path ).exists() but File takes a URI not a URL as a constructor param. If it's a file, I can just do this, right?:
    try
         InputStream in = url.openStream();
         in.close();
    catch (IOException e)
         //Assume doesn't exist?
    }But if it's a jar file, that won't work since you can only open a stream to an entry. So for jar files, I do this, right?
    try
         URLConnection conn = url.openConnection();
         if ( conn instanceof JarURLConnection ) ( ( JarURLConnection ) conn ).getJarFile();
    catch (IOException e)
         //Assume doesn't exist?
    }Is there a better way?

    Hi,
    Try the below method which convert the given URL to and check if the file exists
    public boolean isFileExistGivenURL (URL url) {
              if (url == null || !url.getProtocol().equals("file")) {
                return false;
            } else {
                String filename = url.getFile().replace('/', File.separatorChar);
                int pos =0;
                while ((pos = filename.indexOf('%', pos)) >= 0) {
                    if (pos + 2 < filename.length()) {
                        String hexStr = filename.substring(pos + 1, pos + 3);
                        char ch = (char) Integer.parseInt(hexStr, 16);
                        filename = filename.substring(0, pos) + ch + filename.substring(pos + 3);
                return new File(filename).exists();
            }Hope this helps
    Regards,
    Alan Mehio
    London,UK

  • File exist/file not exist

    OK, i create a directory i have read/write permissions on the directory, but still even if the file exists its bringing back the result as if it doesnt i need help with this...
    set serveroutput on
    DECLARE
    fexists    BOOLEAN;
    flen  NUMBER;
    bsize NUMBER;
    BEGIN
    sys.utl_file.fgetattr('TMP_LOCATION', 'test.txt', fexists, flen, bsize);
      IF fexists THEN
        dbms_output.put_line('File Exists');
      ELSE
        dbms_output.put_line('File Does Not Exist');
      END IF;
      dbms_output.put_line('File Length: ' || TO_CHAR(flen));
      dbms_output.put_line('Block Size: ' || TO_CHAR(bsize));
    END fgetattr;
    File Does Not Existmy directory.. CREATE or replace DIRECTORY tmp_location AS 'Server-1\configsheets\completed\pdf approved'

    Good afternoon,
    If you are loooking at a mapped drive, you can only see it if you change how the Oracle services start. You need to have them start with a specific user ID rather than starting as system services. The problem is that the system services cannot see mapped drives.
    So, do this:
    <li>Create a user to be used by Oracle services. Make sure they have the correct rights (I gave mine Server ADMIN so as to have all the access I needed)
    <li>Log into the server and modify the services
    <li>Click the 'Log On' tab and enter the account and password you created for the Oracle Processes
    <li>Reboot the server, allowing the Oracle services to log in with this new ID.
    This should then fix your problem.
    Thanks,
    Don.
    REWARDS: Please remember to mark helpful or correct posts on the forum, not just for my answers but for everyone! :)

  • File Download - new Problem

    Hi java guru's
    I'm trying to write a download pgm using servlet and JSP. The actual problem is, when i'm trying to download a file, the output stream writes all the comtent of the file on the browser itself even if it's a .exe file instead of opening a "Save as" dialog box
    Can you guru's suggest me a best way to overcome this problem!
    Thanks in advance

    Hello friends,
    We can download any files in two ways
    1. calling java script function
    2. read/write operation(io).
    Both codes are working fine. try it and if u face any problem.Please let me know,
    Friendly,
    Jawahar
    bangalore. India
    [email protected]
    =================================
    java script code
    ==============================
    <%
    <!-- file relative path is here -->
    String path ="/jsp/xxx.xls";
    <!-- file name is here -->
    String fileName="xxx.xls";
    %>
    <html>
    <head>
    <title>Down load forms</title>
    </head>
    <body onLoad="window.open('<%=path%>');">
    <table border="0" align="center" width="100%">
    <tr><td height="181"><font face="verdana" color="#5599cc" size="2" align="center">you have selected the file <%=fileName%</font> </td></tr> </table></body></html>
    ==========================================
    Read/write IO operation is here
    ==========================================
    <%
    String files = null;
    String fileName=null;
    <!-- file path is here -->
    String file=".... any path";
    File f = new File(file);
    FileInputStream in = new FileInputStream(f);
    int length = (int)f.length();
    if(length != 0)
    byte[] buf = new byte[length];
    ServletOutputStream op = response.getOutputStream();     
    response.setContentType ("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
    while ((in != null) && ((length = in.read(buf)) != -1))
    System.out.println("BUFFER $"+buf.length+"$");
    System.out.println("Bytes read in: " + Integer.toString(length));
    op.write(buf,0, buf.length);
    op.close();
    %>     
    <%@ page import="java.io.*,javax.servlet.*,java.util.*,java.sql.* " contentType="text/html" %>
    <html>
    <head>
    <title>Welcome to the download form page</title>
    </head>
    <body bgcolor=#FFFFFF>
    ==========================================

Maybe you are looking for