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

Asked

Viewed 2,956 times

1

Hello. I am developing a system where in a certain situation, I must save a file with a picture extension 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? Thanks in advance, now.

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();
            }
        }
    }

}

1 answer

4


You can do this through function .exists();, 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.
}
  • 1

    It worked out! Thank you Avelino.

  • For nothing, I hope I’ve helped. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.