Java Eclipse 上传图片到包内的图片文件夹

Java Eclipse upload image to image folder within package

我正在使用 Swing Jframe 在 eclipse 中工作。我目前有一个上传按钮,单击该按钮后,我需要它允许用户浏览图像并将其上传(技术上复制并重命名)到我的 Java 项目中名为 images 的文件夹中。 然后我将在稍后引用文件路径并显示图像。任何帮助都会很棒!

    JButton uploadButton = new JButton("Upload...");
    uploadButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //TODO
        }
    });
    uploadPanel.add(uploadButton, BorderLayout.SOUTH);
    return uploadPanel;

希望这有助于回答您的问题:)

// Choose file
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);

// Make sure that a file was chosen, else exit
if (result != JFileChooser.APPROVE_OPTION) {
    System.exit(0);
}

// Get file path
String path = fc.getSelectedFile().getAbsolutePath();

// Create folder "images" (variable success will be true if a folder was created and false if it did not)
File folder = new File("images");
boolean success = folder.mkdir();
// Get the destination of the folder and the new image (image.jpg will be the new name)
String destination = folder.getAbsolutePath() + File.separator + "img.jpg";

try {
    // Copy file from source to destination
    FileChannel source = new FileInputStream(path).getChannel();
    FileChannel dest = new FileOutputStream(destination).getChannel();
    dest.transferFrom(source, 0, source.size());

    // Close shit
    source.close();
    dest.close();

    System.out.println("Done");
} catch (IOException e) {
    e.printStackTrace();
}