打开没有扩展名的文件 - Java

Opening a file without the extension - Java

我正在为我的大学做一个项目,我的 save/opening 文件工作正常,但我需要将它们保存为我想要的扩展名,并像这样打开。 例如:当我点击保存文件时,我将名称 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 对象
  • 获取其绝对路径作为 String,使用 getAbsolutePath()
  • 检查是否有扩展名:Check file extension in Java
  • 如果没有,请将您的扩展程序添加到路径中:path = path+".txt";
  • 从路径创建一个新的 File 对象:File file = new File(path)
  • Open/Save 文件(您的代码)