Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Example – Renaming a File

Java Example - Renaming a File

Java Examples Java Examples

The following example demonstrates how to rename a file using the File class's oldName.renameTo(newName) method.

Before running the following program, you need to create a test file in the current directory runoob-test.txt.

Main.java File

import

java

.

io

.

File

;

import

java

.

io

.

IOException

;

public

class

RunoobTest

{

public

static

void

main

(

String

[

]

args

)

throws

IOException

{

//

Old file or directory

File

oldName

=

new

File

(

"

./runoob-test.txt

"

)

;

//

New file or directory

File

newName

=

new

File

(

"

./runoob-test-2.txt

"

)

;

if

(

newName

.

exists

(

)

)

{

//

Make sure the new file name does not exist

throw

new

java

.

io

.

IOException

(

"

file exists

"

)

;

}

if

(

oldName

.

renameTo

(

newName

)

)

{

System

.

out

.

println

(

"

Renamed

"

)

;

}

else

{

System

.

out

.

println

(

"

Error

"

)

;

}

}

}

The output of the above code is:



已重命名

Java Examples Java Examples