我正在为我的大学做一个项目,我的保存/打开文件正常工作,但是我需要它们保存为我想要的扩展名,并且也是这样打开的。 例如:当我单击Save File时,我将名称testFile写为文件名并点击保存,现在我的代码必须保存为我想要的扩展名。同样适用于打开文件,如果我编写testFile并打开它,它必须找到testFile.txt。任何人都可以帮我一把,我该怎么做?请按照下面的代码。
private class SalvaDesenho implements ActionListener {
private Component parent;
SalvaDesenho(Component parent) {
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
try {
final JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileNameExtensionFilter("Arquivo de Texto (.txt)", "txt"));
fc.setAcceptAllFileFilterUsed(false);
int returnVal = fc.showSaveDialog(parent);
if (returnVal != JFileChooser.APPROVE_OPTION)
return;
int op = 0;
if (fc.getSelectedFile().exists()) {
Object[] options = { "Sim", "Não" };
op = JOptionPane.showOptionDialog(null, "O arquivo já existe deseja substituilo?", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[1]);
}
if (op != 0) return;
System.out.println("Salvando: " + fc.getSelectedFile().getPath());
FileOutputStream fout = new FileOutputStream(fc.getSelectedFile());
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(figuras);
isSaved = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private class AbreDesenho implements ActionListener {
private Component parent;
AbreDesenho(Component parent) {
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
try {
final JFileChooser fc = new JFileChooser();
FileNameExtensionFilter txtFilter = new FileNameExtensionFilter("Arquivo de texto (.txt)", "txt");
fc.setFileFilter(txtFilter);
int returnVal = fc.showOpenDialog(parent);
if (returnVal != JFileChooser.APPROVE_OPTION)
System.out.println("File error!");
System.out.println("Abrindo: " + fc.getSelectedFile().getPath());
FileInputStream fin = new FileInputStream(fc.getSelectedFile());
ObjectInputStream ois = new ObjectInputStream(fin);
figuras = (Vector<Figura>) ois.readObject();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
pnlDesenho.getGraphics().clearRect(0 , 0, parent.getHeight(), parent.getWidth());
for (int i=0 ; i<figuras.size(); i++)
figuras.get(i).torneSeVisivel(pnlDesenho.getGraphics());
}
}
感谢。
答案 0 :(得分:2)
您必须手动执行此操作:
File
JFileChooser
个对象
String
getAbsolutePath()
的绝对路径
path = path+".txt";
File
File file = new File(path)
对象