Avoiding Overwriting a File : File Utilities « File « Java Tutorial






import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class MainClass {
  public static void main(String[] Args) {
    String filepath = "C:/myFile.txt";
    File aFile = new File(filepath);
    FileOutputStream outputFile = null;
    if (aFile.isFile()) {
      File newFile = aFile;
      do {
        String name = newFile.getName();
        int period = name.indexOf('.');
        newFile = new File(newFile.getParent(), name.substring(0, period) + "_old"
            + name.substring(period));
      } while (newFile.exists());
      aFile.renameTo(newFile);
    }
    try {
      outputFile = new FileOutputStream(aFile);
      System.out.println("myFile.txt output stream created");
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
  }
}








11.55.File Utilities
11.55.1.Ensuring a File Exists
11.55.2.Avoiding Overwriting a File
11.55.3.Copying Files using FileChannel
11.55.4.Format Size
11.55.5.Move File
11.55.6.Compare binary files
11.55.7.Get file date and time
11.55.8.Rename To Temporary Name
11.55.9.Return readable file size with selected value measure
11.55.10.Utility class for synchronizing files/directories
11.55.11.Count files in a directory (including files in all subdirectories)
11.55.12.Extract File Extension
11.55.13.Strip File Extension
11.55.14.Remove File Name Suffix
11.55.15.Get File Name Suffix