2015-03-18 34 views
1

所以我在我的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"; 
} 

回答

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,所以你需要相應地調整你的代碼。

+0

我的教授告訴我必須使用DataInputSteam,DataOutputStream,ReadByte和WriteByte類I: – beginnercoder010812 2015-03-19 01:07:46

+0

在這種情況下,我發現代碼沒有任何問題。奇怪的限制。 '備份文件'應該位於您運行此代碼的當前目錄中。但是當你在這裏得到除了'EOFException'之外的任何異常時,你應該顯示異常的消息,而不是你自己的消息。例如'文件未找到'不是'catch(IOException)'在'EOFException'的catch之後的正確消息。 – EJP 2015-03-19 01:33:39

相關問題