Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Practice makes perfect

Experience is often your best defense against Java pitfalls

  • Print
  • Feedback

Page 8 of 9

Listing 11.2. GoodFileRename.java

package com.javaworld.jpitfalls.article5;
import java.io.*;
public class GoodFileRename
{
    public static void main(String args[])
    {       
        try
        {
            // Check if test file in current dir
            File f = new File("dummy2.txt");
            String name = f.getName();
            if (f.exists())
                System.out.println(f.getName() + " exists.");
            else
                System.out.println(f.getName() + " does not exist.");
            // Attempt to rename with a different extension
            int dotIdx = name.indexOf('.');
            if (dotIdx >= 0)
                name = name.substring(0, dotIdx);
            name = name + ".tst";
            String path = f.getAbsolutePath();
            int lastSep = path.lastIndexOf(File.separator);
            if (lastSep > 0)
                path = path.substring(0,lastSep);
            System.out.println("path: " + path);
            File f3 = new File(path + File.separator + name);
            System.out.println("new name: " + f3.getPath());
            if (f.renameTo(f3))
                System.out.println("Rename to new extension Successful.");
            else
                System.out.println("Rename to new extension failed.");
            
            // Delete the file
            // Fix 1: delete via the "Filename" not File
            if (f3.delete())
                System.out.println("Delete Successful.");
            else
                System.out.println("Delete Failed.");
        } catch (Throwable t)
         {
            t.printStackTrace();   
         }       
    }        
}


A run of Listing 11.2 produces the following output:

  • Print
  • Feedback

Resources