Discuss / Java / 练习

练习

Topic source

保持热爱

#1 Created at ... [Delete] [Delete and Lock User]
static void copy(String source, String target) throws IOException {
    try (InputStream input = new FileInputStream(source);
         OutputStream output = new FileOutputStream(target)) {
        input.transferTo(output);
    }
}

transferTo方法,来自jdk1.9,简化了边读边写操作,以下是源码

public long transferTo(OutputStream out) throws IOException {
    Objects.requireNonNull(out, "out");
    long transferred = 0;
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    int read;
    while ((read = this.read(buffer, 0, DEFAULT_BUFFER_SIZE)) >= 0) {
        out.write(buffer, 0, read);
        transferred += read;
    }
    return transferred;
}

  • 1

Reply