Java Create, Write, Delete Text File

How To Create And Write And Delete Txt File Using Java NetBeans

java create writr remove text file



In this Java tutorial will demonstrate how to create a text file with a custom name and write data from a jTextArea into the file. Additionally, we will learn how to remove the file using the FileWriter and BufferedWriter classes in Java NetBeans, all in a step-by-step manner .




Project Source Code:


// create and write in text file
private void jButtonCreateAndWriteActionPerformed(java.awt.event.ActionEvent evt) {                                                      
      
        String filePath = jTextFieldFilePath.getText();
        
        File file = new File(filePath);
        
        if(!file.exists()){
            try {
                
                file.createNewFile();
                FileWriter wr = new FileWriter(file);
                BufferedWriter bw = new BufferedWriter(wr);
                
                bw.write(jTextArea1.getText());
                
                bw.close();
                wr.close();
                
            } catch (IOException ex) {
                Logger.getLogger(TxtFile_Create_Write_Delete.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
    }                                                     

   // delete file
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        
        String filePath = jTextFieldFilePath.getText();
        
        File file = new File(filePath);
        
        if(file.exists()){
            file.delete();
        }
        
    } 


OutPut:

create write delete text file using java



Share this

Related Posts

Previous
Next Post »