Copy a file in Java | Techie Delight

import

java

.

io

.

File

;

import

java

.

io

.

FileInputStream

;

import

java

.

io

.

FileOutputStream

;

import

java

.

io

.

IOException

;

import

java

.

nio

.

channels

.

FileChannel

;

 

class

Main

{

    

public

static

void

copyFile

(

File

src

,

File

dest

)

throws

IOException

{

        

try

(

FileChannel

sourceChannel

=

new

FileInputStream

(

src

)

.

getChannel

(

)

;

                

FileChannel

destChannel

=

new

FileOutputStream

(

dest

)

.

getChannel

(

)

)

{

            

destChannel

.

transferFrom

(

sourceChannel

,

0

,

sourceChannel

.

size

(

)

)

;

        

}

    

}

 

    

public

static

void

main

(

String

[

]

args

)

    

{

        

File

from

=

new

File

(

“src.txt”

)

;

        

File

to

=

new

File

(

“dest.txt”

)

;

 

        

try

{

            

copyFile

(

from

,

to

)

;

            

System

.

out

.

println

(

“File copied successfully.”

)

;

        

}

        

catch

(

IOException

ex

)

{

            

ex

.

printStackTrace

(

)

;

        

}

    

}

}