Membuat program membaca dan menulis file text menggunakan java IO:
Rancangan GUI Program
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
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");
}