伊莉討論區
標題:
IO檔案複製
[打印本頁]
作者:
hctar
時間:
2012-12-22 12:41 AM
標題:
IO檔案複製
功能是讀取一檔案(在c1輸入名稱),然後在c2打上複製後的新名稱,但兩個文件的內容是一樣的,只是複製檔案後更改名稱,當c1與c2設定完成後,按下b1進行檔案複製,我想請問一下按鈕的部分如何寫讓他執行檔案複製的函式?
import java.applet.Applet;
public class 測試 extends Applet implements ActionListener {
private Button b1=new Button(" Go ");
private Button b2=new Button("Cancel");
private static TextField c1=new TextField(30);
private static TextField c2=new TextField(30);
private Label l1=new Label("Enter source file_name:");
private Label l2=new Label("Enter destination file_name:");
public void init()
{
resize(300,300);
add(l1); add(c1); add(l2); add(c2); add(b1); add(b2);
b1.addActionListener(this); b2.addActionListener(this);
c1.addActionListener(this); c2.addActionListener(this);
}
public void paint(Graphics g)
{
b1.setLocation(80,200);b2.setLocation(170,200);
c2.setLocation(35,100);
}
public Button getB1()
{return b1;}
public Button getB2()
{return b2;}
public static void main() throws IOException,FileNotFoundException{
try{
int k;
int i=0;
String f1,f2;
f1=c1.getText();
f2=c2.getText();
FileInputStream a=new FileInputStream(f1);
FileOutputStream r=new FileOutputStream(f2);
while ((k=a.read()) !=-1)
{
i++;
r.write(k);
}
a.close();
r.close();
System.exit(0);
}
catch(Exception e1)
{
e1.printStackTrace();
}
}
public void actionPerformed(ActionEvent e) {
}
}
複製代碼
作者:
louisz6ster
時間:
2012-12-22 09:47 AM
1.可以把main method檔案複製那一段程式碼,放到actionPerformed
2.把檔案複製獨立出來一個method,actionPerformed執行那段method
另外檔案複製可以改成FileChannel速度會有很大的提升喔。
FileInputStream source = new FileInputStream(srcFile);
FileOutputStream destination = new FileOutputStream(destFile);
FileChannel sourceFileChannel = source.getChannel();
FileChannel destinationFileChannel = destination.getChannel();
long size = sourceFileChannel.size();
sourceFileChannel.transferTo(0, size, destinationFileChannel);
複製代碼
歡迎光臨 伊莉討論區 (http://eyny.com/)
Powered by Discuz!