在我的应用程序中,我想用不同的名称保存某个文件的副本(我从用户那里获得)

我真的需要打开文件的内容并将其写入另一个文件吗?

最好的方法是什么?

推荐答案

要复制文件并将其保存到目标路径,可以使用以下方法.

public static void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dst);
        try {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

在API 19+上,您可以使用Java自动资源管理:

public static void copy(File src, File dst) throws IOException {
    try (InputStream in = new FileInputStream(src)) {
        try (OutputStream out = new FileOutputStream(dst)) {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
    }
}

Java相关问答推荐

@从类文件中删除JsonProperty—Java

即使我正在使用并发方法,使用Javascript的应用程序也会继续冻结'

RxJava PublishSubject缓冲区元素超时

为什么BasicComboBoxRenderer在文本不存在或文本为空的情况下设置两次文本?

Character::Emoji不支持带数字的字符吗?

@ IdClass with @ Inheritance(策略= InheritanceType. SINGLE_TABLE)

在运行MVN测试时,为什么构建失败,并显示了java.lang.ClassNotFoundException:java.net.http.HttpResponse?

呈现文本和四舍五入矩形时出现的JavaFX窗格白色瑕疵

Spring Data JPA慢慢地创建了太多非活动会话

OpenGL ES 3.0-纹理黑色

如何让JavaFx应用程序识别依赖项?

Arrays.hashcode(int[])为不同的元素提供相同的散列

Android Studio模拟器没有互联网

嘲笑黄瓜中的对象

如何在Maven Central上部署?

为什么Spring要更改Java版本配置以及如何正确设置?

如何在Selenium上继续使用最新的WebDriver版本

如何正确使用java.time类?

始终使用Spring Boot连接mongodb上的测试数据库

[Guice/MissingImplementation]:未绑定任何实现