java - 这是备份带有流和异常的文件的正确方法吗?

标签 java

所以我在我的java代码中编写了一个简单的备份文件方法,但是当我在测试类中测试该方法并再次检查我的文件夹时,即使我收到成功消息,我也没有看到创建的副本或备份文件。这是正确的还是我遗漏了什么?

import java.io.*;
import java.util.ArrayList;
import javax.swing.*;

public class BasicFile {

File file1;
JFileChooser selection;
File file2 = new File(".", "Backup File");

public BasicFile() {
    selection = new JFileChooser(".");
}

public void selectFile() {
    int status = selection.showOpenDialog(null);

    try {
        if (status != JFileChooser.APPROVE_OPTION) {
            throw new IOException();
        }
        file1 = selection.getSelectedFile();

        if (!file1.exists()) {
            throw new FileNotFoundException();
        }
    } catch (FileNotFoundException e) {
        JOptionPane.showMessageDialog(null, "File Not Found ", "Error", JOptionPane.INFORMATION_MESSAGE);
    } catch (IOException e) {
        System.exit(0);
    }
}

public void backupFile() throws FileNotFoundException {
    DataInputStream in = null;
    DataOutputStream out = null;
    try {
        in = new DataInputStream(new FileInputStream(file1));
        out = new DataOutputStream(new FileOutputStream(file2));

        try {
            while (true) {
                byte data = in.readByte();
                out.writeByte(data);
            }
        } catch (EOFException e) {
            JOptionPane.showMessageDialog(null, "File has been backed up!",
                    "Backup Complete!", JOptionPane.INFORMATION_MESSAGE);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "File Not Found ",
                    "Error", JOptionPane.INFORMATION_MESSAGE);
        }
    } finally {
        try {
            in.close();
            out.close();
        } catch (Exception e) {
            display(e.toString(), "Error");
        }
    }

}

boolean exists() {
    return file1.exists();
}

public String toString() {
    return file1.getName() + "\n" + file1.getAbsolutePath() + "\n" + file1.length() + " bytes";
}

最佳答案

这是正确的,但效率非常低。您也不需要 DataInputStreamDataOutputStream。在 Java 中复制流的规范方法是:

int count;
byte[] buffer = new byte[8192]; // or more if you like
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

此代码不会抛出 EOFException,因此您需要相应地调整代码。

关于java - 这是备份带有流和异常的文件的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29134535/

相关文章:

java - 为什么我会收到 GAE 应用程序的 ClassNotFoundException

java - 无法识别自定义用户存储管理器 (WSOIS 5.3)

java - 在无状态 EJB 中缓存 MessageProducer 和/或 jms session

java - 使用比硬件线程更多的线程时的注意事项?

java - bean 类的属性 'maximumActive' 无效

java - 在 Swing 中显示 XHTML (JEditorPane)

java - 使用 KeyCzar 对 Android 进行非对称加密

Java:数组中的索引存在,ArrayIndexOutOfBoundsException:0

java - 如何将此 unix 时间字符串转换为 java 日期

java - period. Between 不包括 Java 中的最后一天