How to check if a file already exists and overwrite it in Java?

1

Hello. I am developing a system where in a certain situation, I must save a file with an extension of figures created by me. If the file already exists, I check with the user if he wants to overwrite the existing file. How should I proceed? Thank you in advance.

private class SalvarArquivo implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        Figura figura;
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Salvar como");

        int retrival = fileChooser.showSaveDialog(null);
        if (retrival == JFileChooser.APPROVE_OPTION) {

            try {

                String nome_arquivo = FileChooser.getSelectedFile().getAbsolutePath();
                if (!nome_arquivo.endsWith(".xyz")) {
                    nome_arquivo += ".xyz";
                }

                File arquivo1 = new File(nome_arquivo);

                PrintWriter pw = new PrintWriter(arquivo1);

                    for (int i = 0; i < figuras.size(); i++) {
                    figura = figuras.get(i);
                    pw.println(figura.toString());

                }

                pw.close();

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

}
    
asked by anonymous 15.05.2015 / 04:32

1 answer

4

You can do this through the .exists(); function, for example:

boolean exists = (new File("pasta/cadastros.txt")).exists();
if (exists) {
    //Faz alguma coisa
} else {//Se não existe, cria o arquivo...
    File file = new File("pasta");
    file.mkdir();//Cria uma pasta chamada "pasta"
    PrintWriter out = new PrintWriter("pasta/arquivo.txt"); //Cria arquivo.txt
    out.println("1ª linha");
    out.println("2ª linha");
    out.close();//Encerra escrita.
}
    
15.05.2015 / 04:41