Membuat, Membaca dan Menulis File Menggunakan Java Netbeans

Dari java, kita bisa membuat file dan sekaligus membaca file. Caranya adalah jalankan aplikasi Netbeans ( kebetulan editor java yang saya pakai adalah Netbeans ).
1.      Selanjutnya buat project baru dengan cara File - new Project
2.      Pada dialog project pilih ‘java’ pada pada categories dan pilih ‘java application’ pada project.


3.      Yang isi perlu anda isikan adalah :
Project Name         : File
Project Location     : c:\Lat_java
Selanjutnya klik ‘Finish’


4.      Pada project yang terbentuk, buat form baru di package ‘file’ dengan cara klik kanan pada package file - new - JFrame Form …

5.      Ganti Properties title JFrame dengan ‘Read and Write File’

6.      Tambahkan 3 JButton dan 1 JText Area dari Palette kedalam JFrame dan buat text JButton Menjadi seperti berikut :

7.      Setelah JFrame berbentuk seperti diatas, tiba saatnya kita mengisi source code program.
Tambahkan perintah berikut di atas nama class

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
Dan dibawah nama class

private JFileChooser dialog = new JFileChooser();
8.      Isikan source code pada tombol ‘Create File’ dengan cara klik kanan pada JButton ‘Create File’ - Event - Action - ActionPerformed. 

Isikan Source code seperti berikut :

        int returnVal = dialog.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = dialog.getSelectedFile();
            try {
                file.createNewFile();
                PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));               
                out.print(jTextArea1.getText());
                out.flush();  
            } catch (IOException ex) {
                System.err.println("Error: " + ex.getMessage());
            }
        } else {
            JOptionPane.showMessageDialog(null, "Batal Create File ..");
        }
9.      Perintah pada JButton ‘Read File’

            jTextArea1.setText(null);
        int returnVal = dialog.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = dialog.getSelectedFile();
            try{
                FileInputStream fstream = new FileInputStream(file);
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));               
                String strLine;
                while ((strLine = br.readLine()) != null){
                    StringTokenizer st = new StringTokenizer(strLine, ",");
                    jTextArea1.setText(jTextArea1.getText() + st.nextToken() +"\n");
                }
                in.close();
            }catch (Exception e){
                System.err.println("Error: " + e.getMessage());
            }

        } else {
            JOptionPane.showMessageDialog(null, "Batal Buka File ..");
        }

10.  Perintah Pada JButton ‘Close’

             System.exit(0);
11.  Jalankan Program

12. Klik tombol 'Create File' dan 'Read File'


      File Yang dihasilkan dari Proses diatas adalah seperti berikut :


Source Code Selengkapnya :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ReadWrite.java
 *
 * Created on Oct 13, 2010, 1:07:14 PM
 */

package file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author ichwan
 */
public class ReadWrite extends javax.swing.JFrame {   
    private JFileChooser dialog = new JFileChooser();

    /** Creates new form ReadWrite */
    public ReadWrite() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Read and Write File");

        jButton1.setText("Create File");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Read File");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Close");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        System.exit(0);
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        jTextArea1.setText(null);
        int returnVal = dialog.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = dialog.getSelectedFile();
            try{
                FileInputStream fstream = new FileInputStream(file);
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));               
                String strLine;
                while ((strLine = br.readLine()) != null){
                    StringTokenizer st = new StringTokenizer(strLine, ",");
                    jTextArea1.setText(jTextArea1.getText() + st.nextToken() +"\n");
                }
                in.close();
            }catch (Exception e){
                System.err.println("Error: " + e.getMessage());
            }

        } else {
            JOptionPane.showMessageDialog(null, "Batal Buka File ..");
        }
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        int returnVal = dialog.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = dialog.getSelectedFile();
            try {
                file.createNewFile();
                PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));               
                out.print(jTextArea1.getText());
                out.flush();  
            } catch (IOException ex) {
                System.err.println("Error: " + ex.getMessage());
            }
        } else {
            JOptionPane.showMessageDialog(null, "Batal Create File ..");
        }

    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ReadWrite().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration

}

Artikel Lainnya