01010111010101011011000110101010101010110101010111010101011010101010101010101010101010101010101010101010
01010111010101011011000110101010101010110101010111010101011010101010101010101010101010101010101010101010
01010111010101011011000110101010101010110101010111010101011010101010101010101010101010101010101010101010
01010111010101011011000110101010101010110101010111010101011010101010101010101010101010101010101010101010
01010111010101011011000110101010101010110101010111010101011010101010101010101010101010101010101010101010
01010111010101011011000110101010101010110101010111010101011010101010101010101010101010101010101010101010

Java I/O FileReader dan FileWriter

Membuat program membaca dan menulis file text menggunakan java IO:


Rancangan GUI Program
  • Ubah nama variabel JTextArea menjadi textArea
  • Ubah nama variabel button untuk Tampilkan Text menjadi btnTampil
  • Ubah nama variabel button untuk Simpan Text menjadi btnSimpan
Deklarasi package
package TempatText;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
Deklarasi Variable global
File contohFile = new File("storageText.txt");
String text = null;
Isi method btnTampil
private void btnTampilActionPerformed(java.awt.event.ActionEvent evt) {     
if(btnTampil.getText().equals("Tampilkan Text")) {
            try {
                FileReader fileReader = new FileReader(contohFile);
                BufferedReader bufferedReader = new BufferedReader(fileReader);
                while ( ( text = bufferedReader.readLine() ) != null )
                    textArea.append ( text + "\n" ) ;
                    bufferedReader.close();
            }
            catch(IOException ex) {
                ex.printStackTrace();
            }
           btnTampil.setText("Hapus Text");
        }
        else {
            textArea.setText("");
            btnTampil.setText("Tampilkan Text");
        }
}
Isi method btnSimpan
private void btnSimpanActionPerformed(java.awt.event.ActionEvent evt) {                                          
        try {
            String text= textArea.getText();
            FileWriter fileWriter = new FileWriter(contohFile);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(text, 0, text.length());
            bufferedWriter.newLine();
            bufferedWriter.close();
        }
        catch(IOException ex){
            ex.printStackTrace();
        }
        textArea.setText("");
        btnTampil.setText("Tampilkan Text");
    } 
Share this article :
 
 
Support : Creating Website | Mohammad Mastur
Copyright © 2011. Catatan Harianku - All Rights Reserved
Template Created by Creating Website Published by Mohammad Mastur
Proudly powered by Blogger