gpt4 book ai didi

java - 打开不带扩展名的文件 - Java

转载 作者:行者123 更新时间:2023-12-02 04:38:36 25 4
gpt4 key购买 nike

我正在为我的大学做一个项目,我的保存/打开文件工作正常,但我需要它们保存为我想要的扩展名,并像这样打开。例如:当我单击“保存文件”时,我将名称 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());
}
}

谢谢。

最佳答案

您必须手动执行此操作:

  • JFileChooser 获取 File 对象
  • 使用 getAbsolutePath()String 形式获取其绝对路径。
  • 检查是否有扩展名:Check file extension in Java
  • 如果没有,请将您的扩展名添加到路径中:path = path+".txt";
  • 从路径创建一个新的File对象:File file = new File(path)
  • 打开/保存文件(您的代码)

关于java - 打开不带扩展名的文件 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30463911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com