-1

Java swing を使用して、ある場所から別の場所にコピーするためのコードを実行しています。のためにここにしましたBrowse。しかし、コピーボタンの機能を追加する方法がわかりません。コードを手伝ってください。前もって感謝します。これが私の完全なコードです。(初めて使うので間違っていたらごめんなさい)

/*
 For Browse button. 
 */
package com.design;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Browse extends JFrame implements 

ActionListener {

JButton button1, button2 ;
JTextField field1, field2;

public Browse () {
this.setLayout(null);

button1 = new JButton("Browse");
field1 = new JTextField();

field1.setBounds(30, 50, 200, 25);
button1.setBounds(240, 50, 100, 25);
this.add(field1);
this.add(button1);

button2 = new JButton("Copy");
button2.setBounds(150, 150, 100, 25);
this.add(button2);

button1.addActionListener(this);
setDefaultCloseOperation

(javax.swing.WindowConstants.EXIT_ON_CLOSE

);



}

public void actionPerformed(ActionEvent e) {
Chooser frame = new Chooser();
field1.setText(frame.fileName);

}

public static void main(String args[]) {

Browse frame = new Browse ();
frame.setSize(400, 300);
frame.setLocation(200, 100);
frame.setVisible(true);


}
}

class Chooser extends JFrame {

JFileChooser chooser;
String fileName;

public Chooser() {
chooser = new JFileChooser();
int r = chooser.showOpenDialog(new JFrame());
if (r == JFileChooser.APPROVE_OPTION) {
fileName = chooser.getSelectedFile().getPath();
System.out.println(fileName);
}
}
}
4

1 に答える 1

1

これは、Java 7 でファイルをコピーするためのスニペットです。

try {
    Files.copy(new File(your_source_file).toPath(), new File(your_target_file).toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}

ただし、Java 6 以前のバージョンでもサポートされているかどうかはわかりません。したがって、これはすべての Java バージョンで動作する「DIY」スニペットですtrue。ファイルがコピーされている場合は返され、false例外がスローされた場合は次のようになります。

public boolean copyfile(String sourceFile, String targetFile) {
   try {
      File f1 = new File(sourceFile);
      File f2 = new File(targetFile);
      InputStream in = new FileInputStream(f1);

      //Write to the new file
      OutputStream out = new FileOutputStream(f2);

      byte[] buf = new byte[1024];
      int len;
      while ((len = in.read(buf)) > 0) {
         out.write(buf, 0, len);
      }
      in.close();
      out.close();
      System.out.println("File copied.");
   } catch (Exception ex) {
      ex.printStackTrace();
      return false;
   }
   return true;
}

お役に立てれば

于 2013-03-03T10:53:43.347 に答える