我正在尝试编写一个复制一个文件并将其内容复制到另一个文件的程序。我必须让用户选择文件。我被困了可以请一些人帮助我。
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import javax.swing.JFileChooser;
public class FileCopy {
public static void main(String[]Args) throws IOException {
JFileChooser chooser = new JFileChooser("/Users/josealvarado/Desktop/");
Path FROM = Paths.get(chooser);
Path TO = Paths.get(chooser);
//overwrite existing file, if exists
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(FROM, TO, options);
}
}
答案 0 :(得分:1)
我只能猜到,但我认为你需要一个包含你的JFileChooser的JFrame,我做了一个没有任何功能的小例子,只是为了展示你怎么可能达到你的目标。
请在此处了解您的下一个问题,发布您尝试的内容并发布您获得的错误/异常,否则很难帮助或解决您的问题!
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.professional_webworkx.tutorial.jtable.view;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
/**
*
* @author ottp
*/
public class MainFrame extends JFrame {
private JFileChooser chooser;
public MainFrame() {
initGUI();
}
private void initGUI() {
chooser = new JFileChooser();
chooser.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(chooser.getSelectedFile().getName());
}
});
this.setTitle("FileChoosing and copy one file to another");
this.setSize(1024, 768);
this.getContentPane().add(chooser, BorderLayout.NORTH);
this.setVisible(true);
}
}
启动应用程序的类
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.professional_webworkx.tutorial.jtable;
import de.professional_webworkx.tutorial.jtable.view.MainFrame;
import javax.swing.JFileChooser;
/**
*
* @author ottp
*/
public class JTableDemo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new MainFrame();
}
}
希望这有帮助, 帕特里克
答案 1 :(得分:1)
Path FROM = Paths.get(chooser);
Path TO = Paths.get(chooser)
您无法将JFileChooser
传递给Paths.get()
。以下是重载的静态方法
Paths.get(String first, String... more)
- 将路径字符串或从路径字符串连接时的字符串序列转换为路径。Paths.get(URI uri)
- 将给定的URI转换为Path对象。您可能希望传递一个字符串。为此,您需要从String
获取JFileChooser
文件路径。要做到这一点,首先需要chooser.showOpenDialog()
,如果在选择文件(int
)后按下确定按钮,则返回APPROVE_OPTION
,所以你想要做这样的事情
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(null);
String path;
if (result == JFileChooser.APPROVE_OPTION) {
path = (chooser.getSelectedFile()).getAbsolutePath();
}
然后您可以将path
传递给Paths.get(path)