Review notes for Java 1.7 and later file copies

Overview

This is a review of file copying that can be done only with the standard API of Java 1.7 or later.

environment

reference

Files#copy() (Java 1.7+)

This is a method using the copy method of the Files class added in Java 1.7.

signature


public static long copy​(InputStream in, Path target, CopyOption... options) throws IOException

public static long copy​(Path source, OutputStream out) throws IOException

public static Path copy​(Path source, Path target, CopyOption... options) throws IOException

** Code example 1 **

example


Path source = Paths.get("path/to/in.txt");
Path target = Paths.get("path/to/out.txt");
Files.copy(source, target);

If you want to overwrite the copy destination file, specify REPLACE_EXISTING in the copy option.

example


Path source = Paths.get("path/to/in.txt");
Path target = Paths.get("path/to/out.txt");
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);

If you want to copy to any directory. In this example, "path / to / in.txt" is copied to "path / to / newDir / in.txt".

example


Path source = Paths.get("path/to/in.txt");
Path targetDir = Paths.get("path/to/newDir");
Files.copy(source, targetDir.resolve(source.getFileName()));

** Code example 2 **

example


InputStream source = Files.newInputStream(Paths.get("path/to/in.txt"));
Path target = Paths.get("path/to/out.txt");
try (source) {
  Files.copy(source, target);
}

InputStream.transferTo (Java 9+)

This is a method using the transferTo method added in Java 9 to the InputStream class.

signature


public long transferTo​(OutputStream out) throws IOException

transferTo does not close the reader / writer stream as described in the JavaDoc (Machine Translation).

Reads all bytes from this input stream and writes the bytes to the specified output stream in the order they were read. On return, this input stream is at the end of the stream. This method does not close any stream.

** Known subclass **

The value in () is the Java version in which the class and interface are installed.

InputStream (1.0)
 |
 +--- javax.sound.sampled.AudioInputStream (1.3)
 |
 +--- ByteArrayInputStream (1.0)
 |
 +--- FileInputStream (1.0)
 |
 +--- FilterInputStream (1.0)
 |     |
 |     +--- BufferedInputStream (1.0)
 |     +--- java.util.zip.CheckedInputStream (1.1)
 |     +--- javax.crypto.CipherInputStream (1.4)
 |     +--- DataInputStream (1.0)
 |     +--- java.util.zip.DeflaterInputStream (1.6)
 |     +--- java.security.DigestInputStream (1.2)
 |     +--- java.util.zip.InflaterInputStream (1.1)
 |     |    @Deprecated
 |     +--- LineNumberInputStream (1.0)
 |     +--- javax.swing.ProgressMonitorInputStream (1.2)
 |     +--- PushbackInputStream (1.0)
 |
 +--- org.omg.CORBA.portable.InputStream
 |
 +--- ObjectInputStream (1.1)
 |
 +--- PipedInputStream (1.0)
 |
 +--- SequenceInputStream (1.0)
 |
 |    @Deprecated
 +--- StringBufferInputStream (1.0)

FileInputStream.transferTo

** Code example 1 **

example


Path source = Paths.get("path/to/in.txt");
Path target = Paths.get("path/to/out.txt");
try (InputStream in = new FileInputStream(source.toFile());
     OutputStream out = new FileOutputStream(target.toFile())) {
  in.transferTo(out);
}

** Code example 1 (Java 9+) **

Starting with Java 9, resources can be declared outside the try clause.

example


Path source = Paths.get("path/to/in.txt");
Path target = Paths.get("path/to/out.txt");
InputStream in = new FileInputStream(source.toFile());
OutputStream out = new FileOutputStream(target.toFile());
try (in; out) {
  in.transferTo(out);
}

** Code example 2 **

example


Path source = Paths.get("path/to/in.txt");
Path target = Paths.get("path/to/out.txt");
try (InputStream in = Files.newInputStream(source);
     OutputStream out = Files.newOutputStream(target)) {
    in.transferTo(out);
}

** Code example 2 (Java 9+) **

example


Path source = Paths.get("path/to/in.txt");
Path target = Paths.get("path/to/out.txt");
InputStream in = Files.newInputStream(source);
OutputStream out = Files.newOutputStream(target);
try (in; out) {
    in.transferTo(out);
}

Reader.transferTo (Java 10+)

It is a method to use the transferTo method added in Java 10 to the Reader class.

signature


public long transferTo​(Writer out) throws IOException

transferTo does not close the reader / writer stream as described in the JavaDoc (Machine Translation).

Reads all characters from this reader and writes them to the specified writer in the order they were read. When you come back, this leader is at the end of the stream. This method does not close either the reader or the writer.

** Known subclass **

The value in () is the Java version in which the class and interface are installed.

Reader
 |
 +--- BufferedReader (1.1)
 |     |
 |     +--- LineNumberReader (1.1)
 |
 +--- CharArrayReader (1.1)
 |
 +--- FilterReader (1.1)
 |     |
 |     +--- PushbackReader (1.1)
 |
 +--- InputStreamReader (1.1)
 |     |
 |     +--- FileReader (1.1)
 |
 +--- PipedReader (1.1)
 |
 +--- StringReader (1.1)
 |
 +--- jdk.nashorn.api.scripting.URLReader (1.8u40)

FileReader.transferTo

** Code example **

example


Path source = Paths.get("path/to/in.txt");
Path target = Paths.get("path/to/out.txt");
Reader in = new FileReader(source.toFile());
Writer out = new FileWriter(target.toFile());
try (in; out) {
  in.transferTo(out);
}

BufferedReader.transferTo

It is recommended to wrap InputStreamReader and FileReader with BufferedReader.

Generally, when a read request is made to Reader, a read request to the corresponding underlying character stream or byte stream is issued. For this reason, it is recommended to wrap the area around the Reader with an inefficient read () operation, such as FileReader and InputStreamReader.

Similarly, it is recommended to wrap OutputStreamWriter and FileWriter with BufferedWriter.

In general, the Writer immediately sends its output to the underlying character or byte stream. It is inefficient to call the write () operation directly from a Writer like FileWriter or OutputStreamWriter unless you need prompt output, so it is recommended to wrap it in a BufferedWriter.

** Code example **

You can rewrite the FileReader code example as follows.

example


BufferedReader in = new BufferedReader(new FileReader(source.toFile()));
BufferedWriter out = new BufferedWriter(new FileWriter(target.toFile()));
try (in; out) {
  in.transferTo(out);
}

StringReader.transferTo

** Code example **

example


String source = "Water striders\n red\n Aiueo";
Path target = Paths.get("path/to/out.txt");
Reader in = new StringReader(source);
Writer out = new FileWriter(target.toFile());
try (in; out) {
  in.transferTo(out);
}

URLReader.transferTo

The URLReader class was added in Java 1.8u40.

** Deprecated in Java 11 ** (JEP 335: Deprecate the Nashorn JavaScript Engine).

** Code example **

example


URI source = URI.create("http://www.oracle.com/technetwork/java/index.html");
Path target = Paths.get("path/to/out.txt");
Reader in = new URLReader(source.toURL(), StandardCharsets.UTF_8);
Writer out = new FileWriter(target.toFile());
try (in; out) {
  in.transferTo(out);
}

(WIP) Files#writeString (Java 11+)

This is a method using the writeString method added in Java 11 to the Files class.

public static Path writeString​(Path path, CharSequence csq, OpenOption... options) throws IOException

public static Path writeString​(Path path, CharSequence csq, Charset cs, OpenOption... options) throws IOException

Recommended Posts

Review notes for Java 1.7 and later file copies
Java NIO 2 review notes
Java version 8 and later features
Java Collections Framework Review Notes
Java while and for statements
AWS SDK for Java 1.11.x and 2.x
[Java] Basic types and instruction notes
Java for beginners, expressions and operators 1
Java for beginners, expressions and operators 2
Notes on Java path and Package
Classes and instances Java for beginners
Java review
[Java] for Each and sorted in Lambda
[For beginners] Difference between Java and Kotlin
java notes
Notes for reading and generating xlsx files from Java using Apache POI
[Java] Proxy for logging SQL and SQL results
[Java8] Search the directory and get the file
[Java] Corrective notes for "Invalid escape character" and "Cannot map to encoding MS932"
[Java 7 or later] Prevent temporary file deletion omissions
NullPointerException countermeasure example (Optional) for Java 8 or later
Ask for n business days later with JAVA
I studied for 3 weeks and passed Java Bronze
Java upload and download notes to Azure storage
Kantai Collection Java # 1 Classes and Objects [For Beginners]
Pre-introduction notes for JavaScript experienced learners of Java
Upload and download notes in java on S3
[Java] Convert and import file values with OpenCSV
[Review] Reading and writing files with java (JDK6)
For JAVA learning (2018-03-16-01)
Java Generics (Notes)
Review and implementation of CSV library for loading large amounts of data into MySQL (Java)
[Java] Array notes
Enum review notes
2017 IDE for Java
java file creation
Java and JavaScript
[Java] Study notes
XXE and Java
Java serialization notes
Java IO review
Java for statement
[Java] Let's create a mod for Minecraft 1.14.4 [0. Basic file]
<java> Read Zip file and convert directly to string
Java (jdk1.8 or later) file input / output sample program
Sample (Java) for OAuth 2.0 authentication and access token acquisition
VSCode Java Debugger for Java Build failed Causes and countermeasures
[Java] Let's create a mod for Minecraft 1.16.1 [Basic file]
Learn for the first time java # 3 expressions and operators
[Java] About Objects.equals () and Review of String comparisons (== and equals)
This and that for editing ini in Java. : inieditor-java
List of frequently used Java instructions (for beginners and beginners)
Prepare the environment for java11 and javaFx with Ubuntu 18.4
Gzip-compress byte array in Java and output to file
Summary of file reading method for each Java file format