new File () does not create the file

-1

When creating a program that generates an input file to another program, the problem occurs that the file I try to create with new File() is not created.

Follow the code:

import java.io.File; import java.io.FileWriter; import
java.io.IOException;

import javax.swing.Box; import javax.swing.JFileChooser; import
javax.swing.JFrame; import javax.swing.JLabel; import
javax.swing.JOptionPane; import javax.swing.JPanel; import
javax.swing.JTextField;


public class Gerador extends JFrame {


       public static void main(String[] args) throws IOException {
          JTextField xField = new JTextField(5);
          JTextField yField = new JTextField(5);
          JFileChooser arquivo = new JFileChooser();

          JPanel myPanel = new JPanel();
          myPanel.add(new JLabel("Linhas:"));
          myPanel.add(xField);
          myPanel.add(Box.createHorizontalStrut(15)); // a spacer
          myPanel.add(new JLabel("Colunas:"));
          myPanel.add(yField);


          String in = JOptionPane.showInputDialog("Entre com o nome do arquivo a ser criado!");


          arquivo.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
          arquivo.setDialogTitle("Selecione o diretorio");
          arquivo.setMultiSelectionEnabled(false);
          arquivo.showSaveDialog(null);


          File diretorio = new File(arquivo.getCurrentDirectory().getAbsolutePath());
          File arqEscrita = new File(diretorio, in+".xml");
          FileWriter writer = new FileWriter(arqEscrita);

          System.out.println(arqEscrita);
          if(arqEscrita.createNewFile()){ 
              System.out.println("Arquivo criado em: " + arqEscrita.getAbsolutePath()); 
          } 
          else{ 
              System.out.println("Nao foi possivel criar o arquivo"); 
              }

          int result = JOptionPane.showConfirmDialog(null, myPanel, "Entre com os dados", JOptionPane.OK_CANCEL_OPTION);
          if (result == JOptionPane.OK_OPTION) { 


              try {  

                  writer.write("<?xml version="+"1.0"+" encoding="+"UTF-8"+"?>\n");
                  writer.write("<terreno>\n");        


                  writer.write("</terreno>\n");
                  writer.close();  
              } catch (IOException e) {  
                  e.printStackTrace();  
              } catch (Exception e) {  
                  e.printStackTrace();  
              }  



          }

       }

}
    
asked by anonymous 15.11.2014 / 18:48

1 answer

1

Well I also took a while to find out, the problem is that when you run:

FileWriter writer = new FileWriter(arqEscrita);

This object deletes any file that exists or not and creates a new one. So in that case:

 if(arqEscrita.createNewFile()){ 
     System.out.println("Arquivo criado em: " + arqEscrita.getAbsolutePath()); 
  } 
  else{ 
     System.out.println("Nao foi possivel criar o arquivo"); 
  }

No need.

    
16.11.2014 / 00:02