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

Java Example – Creating a File

Java Example - Creating a File

Java Examples Java Examples

The following example demonstrates how to use the File class's File() constructor and the file.createNewFile() method to create a new file

Main.java File

import

java

.

io

.

File

;

import

java

.

io

.

IOException

;

public

class

Main

{

public

static

void

main

(

String

[

]

args

)

{

try

{

File

file

=

new

File

(

"

C:/myfile.txt

"

)

;

if

(

file

.

createNewFile

(

)

)

System

.

out

.

println

(

"

File created successfully!

"

)

;

else

System

.

out

.

println

(

"

An error occurred; the file already exists.

"

)

;

}

catch

(

IOException

ioe

)

{

ioe

.

printStackTrace

(

)

;

}

}

}

The output of the above code is:



文件创建成功!

Java Examples Java Examples