In this article, you’ll learn how to copy a file or directory in Java using various methods like Files.copy()
or using BufferedInputStream
and BufferedOutputStream
.
Tóm Tắt
Java Copy File using Files.copy()
Java NIO’s Files.copy() method is the simplest way of copying a file in Java.
import
java
.
io.
IOException
;
import
java
.
nio.
file.
*
;
public
class
CopyFileExample
{
public
static
void
main
(
String
[
]
args)
{
Path
sourceFilePath =
Paths
.
get
(
"./bar.txt"
)
;
Path
targetFilePath =
Paths
.
get
(
System
.
getProperty
(
"user.home"
)
+
"/Desktop/bar-copy.txt"
)
;
try
{
Files
.
copy
(
sourceFilePath,
targetFilePath)
;
}
catch
(
FileAlreadyExistsException
ex)
{
System
.
out.
println
(
"File already exists"
)
;
}
catch
(
IOException
ex)
{
System
.
out.
format
(
"I/O error: %s%n"
,
ex)
;
}
}
}
The Files.copy()
method will throw FileAlreadyExistsException
if the target file already exists. If you want to replace the target file then you can use the REPLACE_EXISTING
option like this –
Files
.
copy
(
sourceFilePath,
targetFilePath,
StandardCopyOption
.
REPLACE_EXISTING)
;
Note that, Directories can be copied using the same method. However, files inside the directory are not copied, so the new directory will be empty even when the original directory contains files.
Java Copy File using BufferedInputStream and BufferedOutputStream
You can also copy a file byte-by-byte using a byte-stream I/O. The following example uses BufferedInputStream
to read a file into a byte array and then write the byte array using BufferedOutputStream
.
You can also use a FileInputStream
and a FileOutputStream
directly for performing the reading and writing. But a Buffered I/O is more performant because it buffers data and reads/writes it in chunks.
import
java
.
io.
*
;
import
java
.
nio.
file.
Files
;
import
java
.
nio.
file.
Path
;
import
java
.
nio.
file.
Paths
;
public
class
CopyFileExample1
{
public
static
void
main
(
String
[
]
args)
{
Path
sourceFilePath =
Paths
.
get
(
"./bar.txt"
)
;
Path
targetFilePath =
Paths
.
get
(
System
.
getProperty
(
"user.home"
)
+
"/Desktop/bar-copy.txt"
)
;
try
(
InputStream
inputStream =
Files
.
newInputStream
(
sourceFilePath)
;
BufferedInputStream
bufferedInputStream =
new
BufferedInputStream
(
inputStream)
;
OutputStream
outputStream =
Files
.
newOutputStream
(
targetFilePath)
;
BufferedOutputStream
bufferedOutputStream =
new
BufferedOutputStream
(
outputStream)
)
{
byte
[
]
buffer =
new
byte
[
4096
]
;
int
numBytes;
while
(
(
numBytes =
bufferedInputStream.
read
(
buffer)
)
!=
-
1
)
{
bufferedOutputStream.
write
(
buffer,
0
,
numBytes)
;
}
}
catch
(
IOException
ex)
{
System
.
out.
format
(
"I/O error: %s%n"
,
ex)
;
}
}
}