Contoh Program Java: Operasi File


Dengan operasi file, data yang digunakan dalam aplikasi bisa disimpan secara permanen di hard disk. Sehingga data tidak akan hilang ketika aplikasi di-close atau komputer dimatikan. Operasi file juga memungkinkan penyimpanan data dengan ukuran yang lebih besar (kapasitas hard disk > dari RAM).

Untuk mengoperasikan file digunakan library java.io.File, java.io.FileNotFoundException, java.io.PrintStream dan java.util.Scanner. Library PrintStream dipakai untuk merekam data ke file. Sedangkan library yang dipakai untuk membaca file adalah java.io.File dan java.util.Scanner. Berikut contoh programnya:

import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
import java.io.File;

/**
*
* @author bluejundi
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args)
// TODO code application logic here
throws FileNotFoundException {
//membaca dan menulis file
int npm;
String nama = new String(“”);
double ipk;
PrintStream diskWriter = new PrintStream(“mhs.txt”);
int i;
Scanner sc = new Scanner(System.in);
System.out.print(“Jumlah data = “);
i = sc.nextInt();
do
{
System.out.print(“NPM = “);
npm = sc.nextInt();
System.out.print(“Nama = “);
nama = sc.next();
System.out.print(“IPK = “);
ipk = sc.nextDouble();
diskWriter.println(npm + ” ” + nama + ” ” + ipk);
i–;
}
while(i>0);
System.out.println(“Isi File:”);
Scanner diskScanner = new Scanner(new File(“mhs.txt”));
while (diskScanner.hasNext())
{
npm = diskScanner.nextInt();
nama = diskScanner.next();
ipk = diskScanner.nextDouble();
System.out.println(“[" + npm + "] ” + nama + ” (” + ipk + “)”);
}
}
}

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 44 other followers

%d bloggers like this: