要将JFileChooser中的文件保存到项目文件夹中,可以按照以下步骤进行操作:
以下是一个示例代码,演示了如何将JFileChooser中的文件保存到项目文件夹中:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
public class FileSaveExample {
public static void main(String[] args) {
JFrame frame = new JFrame("File Save Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton saveButton = new JButton("Save File");
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showSaveDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
String fileName = selectedFile.getName();
String filePath = selectedFile.getParent();
String targetFolderPath = "项目文件夹的路径"; // 替换为实际的项目文件夹路径
String targetFilePath = targetFolderPath + File.separator + fileName;
try {
FileInputStream fis = new FileInputStream(selectedFile);
FileOutputStream fos = new FileOutputStream(targetFilePath);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.close();
fis.close();
JOptionPane.showMessageDialog(frame, "文件保存成功!");
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, "文件保存失败!");
}
}
}
});
frame.getContentPane().add(saveButton);
frame.pack();
frame.setVisible(true);
}
}
请注意,上述示例代码中的"项目文件夹的路径"需要替换为实际的项目文件夹路径。另外,该示例代码只是一个简单的演示,实际应用中可能需要考虑更多的异常处理和用户交互。
领取专属 10元无门槛券
手把手带您无忧上云