Di sini kita buat sebuah kelas yang berisi method untuk menulis dan membaca file teks. Ada banyak cara untuk membaca dan menulis file dalam Java. Di sini kita menggunakan cara yang sangat serderhana.
Berikut ini adalah kelasnya:
- BufferReader dan BufferWriter
/*
* To change this license header, choose
License Headers in Project Properties.
* To change this template file, choose Tools |
Templates
* and open the template in the editor.
*/
package
mhspoltek2016;
import
java.io.BufferedReader;
import
java.io.BufferedWriter;
import
java.io.FileReader;
import
java.io.FileWriter;
import
java.util.StringTokenizer;
import
java.util.Vector;
import
javax.swing.JOptionPane;
import
javax.swing.SwingConstants;
import
javax.swing.table.DefaultTableCellRenderer;
import
javax.swing.table.DefaultTableModel;
/**
*
* @author ASUS X450J
*/
public
class utama extends javax.swing.JFrame {
/**
* Creates new form utama
*/
private Vector<Vector<String>>
DB = new Vector(), data = new Vector();
private Vector head = new Vector();
private int max = 0;
private String fileName =
"D:/dataMahasiswa.txt";
private DefaultTableCellRenderer
rightRenderer = new DefaultTableCellRenderer();
public utama() {
initComponents();
rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
bacaData();
updateTabel();
}
private void bacaData(){
try {
BufferedReader br = new
BufferedReader(new FileReader(fileName));
String tmp;
while((tmp=br.readLine())!=null){
StringTokenizer st = new
StringTokenizer(tmp, "#");
Vector<String> tmp2 = new
Vector();
String No = st.nextToken();
String NIM = st.nextToken();
String Nama = st.nextToken();
String Alamat = st.nextToken();
tmp2.add(No); tmp2.add(NIM);
tmp2.add(Nama); tmp2.add(Alamat);
DB.add(tmp2);
if(Integer.parseInt(No) >
max) max = Integer.parseInt(No);
}
br.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private void simpanData(){
try {
BufferedWriter bw = new
BufferedWriter(new FileWriter(fileName));
for (Vector<String> v : DB) {
bw.write(v.get(0)+"#"+v.get(1)+"#"+v.get(2)+"#"+v.get(3));
bw.newLine();
}
bw.close();
} catch (Exception e) {
}
}
private void
formWindowClosing(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
simpanData();
dispose();
}
Sign up here with your email