这是使用流和异常备份文件的正确方法吗?

时间:2015-03-18 23:23:32

标签: 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";
}

1 个答案:

答案 0 :(得分:0)

这是正确的,但非常低效。您也不需要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,因此您需要相应地调整代码。