Java Reference
In-Depth Information
import java.io.FileNotFoundException;
public class AvoidOverwritingFile {
public static void main(String[] args) {
String filepath = "C:/Beg Java Stuff/myFile.txt";
File aFile = new File(filepath);
FileOutputStream outputFile = null; // Stores the stream reference
if (aFile.isFile()) {
File newFile = aFile; // Start with the original file
// We will append "
_
old" to the file
// name repeatedly until it is unique
do {
String name = newFile.getName(); // Get the name of the file
int period =
name.indexOf('.'); // Find the separator for the extension
newFile = new File(newFile.getParent(),
name.substring(0, period) + "
_
old"
+ name.substring(period));
} while (!aFile.renameTo(newFile)); // Stop when renaming works
}
// Now we can create the new file
try {
// Create the stream opened to append data
outputFile = new FileOutputStream(aFile);
System.out.println("myFile.txt output stream created");
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
}
System.exit(0);
}
}
If you run this a few times, you should see some _
old
_
old
... files created.
How It Works
If the file exists, we execute the code in the
if
block. This stores the reference to the original
File
object in
newFile
as a starting point for the
do-while
loop that follows. Each iteration of the loop
will append the string _
old
to the name of the file and create a new
File
object using this name in the
original directory. The expression in the loop condition then tries to rename the original file using the
new
File
object. If this fails, we go round the loop again and add a further occurrence of _
old
to the
file name. Eventually we should succeed as long as we don't do it so often that we exceed the permitted
file name length of the system. The
getParent()
method gives us the parent directory for the file and
the
getName()
method returns the file name. We have to split the file name into the name part and the
extension to append our _
old
string, and the
charAt()
method for the
String
object gives us the
index position of the separating period. Of course, this code presumes the existence of a file extension
since we define our original file name with one. It is quite possible to deal with files that don't have an
extension but I'll leave that as a little digression for you.