### Rename File

To rename a file, various options possible.
Option using File.Copy and File.Delete
Copy the file using file.copy and then use file.delete to delete the old file.
`Sub renameFile
Dim sFileOld As String = "oldname.txt"
Dim sFileNew As String = "newname.txt"
Try
' Check if file to rename exists
If File.Exists(File.DirApp, sFileOld) = False Then
Log("File to rename not found! " & File.DirApp & " " & sFileOld)
Return
End If
' Copy the file oldname to newname
File.Copy(File.DirApp, sFileOld, File.DirApp, sFileNew)
' Check if the new file exists
If File.Exists(File.DirApp, sFileNew) = False Then
Log("File could not be rename! " & File.DirApp & " " & sFileNew)
Return
End If
' Delete the old file
File.Delete(File.DirApp, sFileOld)
'
Log("Done renaming file " & sFileOld & " to " & sFileNew & " in folder " & File.DirApp)
Catch
Log(LastException.Message)
End Try
End Sub`
Option using JavaObject File Class
The path can contain full and different path, which would be the same as moving a file
Reference: http://docs.oracle.com/javase/8/docs/api/java/io/File.html
`Sub renameFile(source As String, target As String)
Dim joFileSource As JavaObject
Dim joFileTarget As JavaObject
' Create the file instances for the files (the constructor)
joFileSource.InitializeNewInstance("java.io.File", Array As Object(source))
joFileTarget.InitializeNewInstance("java.io.File", Array As Object(target))
' Rename file to
joFileSource.RunMethod("renameTo", Array As Object(joFileTarget))
End Sub`
Example:
renameFile(File.DirTemp & "\testfile.txt", File.DirApp & "\testfile.new")
In addtion, the same pprinciple can be used to Move a File
Move File
'Move file
'Returns True if OK, else False
`Sub FileMove(SourceFolder As String, SourceFile As String, TargetFolder As String, TargetFile As String) As Boolean
Dim source, target As JavaObject
source.InitializeNewInstance("java.io.File", Array(SourceFolder, SourceFile))
target.InitializeNewInstance("java.io.File", Array(TargetFolder, TargetFile))
Return source.RunMethod("renameTo", Array(target))
End Sub`

Changed: , Category: Files, File: T6C193M1393.htm, ID: 1393