伊莉討論區

標題: IO檔案複製 [打印本頁]

作者: hctar    時間: 2012-12-22 12:41 AM     標題: IO檔案複製

功能是讀取一檔案(在c1輸入名稱),然後在c2打上複製後的新名稱,但兩個文件的內容是一樣的,只是複製檔案後更改名稱,當c1與c2設定完成後,按下b1進行檔案複製,我想請問一下按鈕的部分如何寫讓他執行檔案複製的函式?


  1. import java.applet.Applet;
  2. public class 測試 extends Applet implements ActionListener {
  3. private  Button b1=new Button("  Go  ");
  4. private  Button b2=new Button("Cancel");
  5. private  static TextField c1=new TextField(30);
  6. private  static TextField c2=new TextField(30);
  7. private  Label l1=new Label("Enter source file_name:");
  8. private  Label l2=new Label("Enter destination file_name:");
  9. public void init()
  10. {     
  11. resize(300,300);
  12. add(l1); add(c1); add(l2); add(c2); add(b1); add(b2);
  13. b1.addActionListener(this); b2.addActionListener(this);
  14. c1.addActionListener(this); c2.addActionListener(this);
  15. }
  16. public void paint(Graphics g)
  17. {
  18. b1.setLocation(80,200);b2.setLocation(170,200);
  19. c2.setLocation(35,100);
  20. }
  21.    
  22. public Button getB1()
  23. {return b1;}
  24. public Button getB2()
  25. {return b2;}
  26.      
  27.      
  28. public static void main() throws IOException,FileNotFoundException{
  29.    
  30.         try{
  31.             
  32.         int k;
  33.         int i=0;
  34.         String f1,f2;
  35.         f1=c1.getText();
  36.         f2=c2.getText();   
  37.         FileInputStream a=new FileInputStream(f1);
  38.         FileOutputStream r=new FileOutputStream(f2);
  39.          
  40.             while ((k=a.read()) !=-1)
  41.               {   
  42.                i++;
  43.                r.write(k);
  44.               }
  45.             a.close();
  46.             r.close();
  47.             System.exit(0);
  48.             }
  49.             catch(Exception e1)
  50.               {
  51.                 e1.printStackTrace();
  52.               }
  53.         }
  54. public void actionPerformed(ActionEvent e) {

  55.     }
  56. }
複製代碼


作者: louisz6ster    時間: 2012-12-22 09:47 AM

1.可以把main method檔案複製那一段程式碼,放到actionPerformed
2.把檔案複製獨立出來一個method,actionPerformed執行那段method
另外檔案複製可以改成FileChannel速度會有很大的提升喔。
  1. FileInputStream source = new FileInputStream(srcFile);
  2. FileOutputStream destination = new FileOutputStream(destFile);
  3. FileChannel sourceFileChannel = source.getChannel();
  4. FileChannel destinationFileChannel = destination.getChannel();
  5. long size = sourceFileChannel.size();
  6. sourceFileChannel.transferTo(0, size, destinationFileChannel);
複製代碼





歡迎光臨 伊莉討論區 (http://eyny.com/) Powered by Discuz!