File I/O (Input and Output)

Mencari nilai rata-rata, maksimum, dan minimum tanpa menggunakan Array

import java.io.*;
class TanpaArray
{   public static void main(String[] args)
    {   int max=Integer.MIN_VALUE;
        int min=Integer.MAX_VALUE;
        int n=1, x, jml=0;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Masukkan data ke-"+n+" : ");
        try
        {   while((x=Integer.parseInt(br.readLine()))!=0)
            {   if(x>max) max=x;
                if(x<min) min=x;
                jml+=x;
                System.out.println("Masukkan angka ke-"+(++n)+
                                           " [ketik 0 untuk STOP] :");
            }
        } catch(Exception e)
        {
        }
        double rata2=(double) jml/(n-1);
        System.out.println("Total : "+jml);
        System.out.println("Rata-rata : "+rata2);
        System.out.println("Angka terkecil : "+min);
        System.out.println("Angka terbesar : "+max);
    }
}

proses text file (File I/O part III)

import java.io.*;
class HitungNilai
{   
   public static void main(String[] args)
    {   String str;
        int tgs,uts,uas;
        double nilai;
        try
        {   FileReader fr = new FileReader("c:/testdata.txt");
            BufferedReader br = new BufferedReader(fr);
            while((str=br.readLine()) != null)
            {   tgs = Integer.parseInt(str.substring(1,3));
                uts = Integer.parseInt(str.substring(4,6));
                uas = Integer.parseInt(str.substring(7,9));
                nilai=(20*tgs+30*uts+50*uas)/100.0;
                // tambahin di sini untuk konversi jadi nilai huruf
                System.out.printf(" tugas %d  uts % d   uas %d "+
                              " nilai %7.2f\n",tgs,uts,uas,nilai);
            }
            br.close();
        } catch(IOException e)
        {   System.err.println("File read error");
        }
    }
}
substring
misal untuk string st yg isinya "Jalan Merdeka"
st.substring(1,5) --> "Jalan"
st.substring(7,9) --> "Mer"

ini hasilnya (inputnya tebak sendiri dah)
 tugas 80  uts  70   uas 65 nilai 69,50
 tugas 75  uts  60   uas 80 nilai 73,00
 tugas 85  uts  70   uas 95 nilai 85,50
 tugas 65  uts  55   uas 65 nilai 62,00
 tugas 90  uts  95   uas 85 nilai 89,00
 tugas 80  uts  80   uas 75 nilai 77,50

Klik di sini untuk lihat versi yang lebih rumit

Input dan Output ke Text File part II

Pembahasan kali ini mirip dengan pembahasan sebelumnya. Hanya saja kali ini kita akan menggunakan class berbeda dari sebelumnya, walaupun tujuannya sama, yaitu class FileWriter untuk membuat/membuka file text, class BufferedWriter untuk menulis string ke dalam file text, class FileReader untuk membaca file text, dan BufferedReader untuk membaca string pada file text.
versi satu
import java.io.*;
import java.util.Random;
class TulisBacaFile
{   
     static void tulisKeFile(String note)
    {   FileWriter fw;
        BufferedWriter bw = null;
        try
        {   fw = new FileWriter(note);
            bw = new BufferedWriter(fw);
            Random r = new Random();
            int x=0;
            String str=null;
            for(int i=0;i<5;i++)
            {   x = r.nextInt(30)+10;
                str = Integer.toString(x);
                bw.write(str+"\r\n");
                //bw.newLine();
            }
            str = Integer.toString(x+5);
            bw.write(str);
        } catch(IOException e)
        {   System.err.println("File writing error");
        } finally
        {   try
            {   if(bw != null)
                {   bw.flush();
                    bw.close();
                }
            } catch(IOException e)
            {   System.err.println(e);
            }
        }
    }
    
    static void bacaFile(String note)
    {   String str;
        int x, jml=0, n=0;
        try
        {   FileReader fr = new FileReader(note);
            BufferedReader br = new BufferedReader(fr);
            while((str=br.readLine()) != null)
            {   x = Integer.parseInt(str);
                System.out.println(x);
                jml+=x;
                n++;
            }
            br.close();
        } catch(IOException e)
        {   System.err.println("File read error");
        }
        double rata = (double) jml/n;
        System.out.println("Jumlah : "+jml+"\nRata-rata : "+rata);
    }
    
   public static void main(String[] args)
    {   tulisKeFile("coba1.txt");
        bacaFile("coba1.txt");
    }
    
    
}

versi dua
import java.io.*;
import java.util.Random;
class TxtIO
{   public static void main(String[] args)
    {   new TxtIO().tulisKeFile("coba1.txt");
        new TxtIO().bacaFile("coba1.txt");
    }
    void tulisKeFile(String note)
    {   FileWriter fw;
        BufferedWriter bw = null;
        try
        {   fw = new FileWriter(note);
            bw = new BufferedWriter(fw);
            Random r = new Random();
            int x=0;
            String str=null;
            for(int i=0;i<5;i++)
            {   x = r.nextInt(30)+10;
                str = Integer.toString(x);
                bw.write(str+"\r\n");
                //bw.newLine();
            }
            str = Integer.toString(x+5);
            bw.write(str);
        } catch(IOException e)
        {   System.err.println("File writing error");
        } finally
        {   try
            {   if(bw != null)
                {   bw.flush();
                    bw.close();
                }
            } catch(IOException e)
            {   System.err.println(e);
            }
        }
    }
    void bacaFile(String note)
    {   String str;
        int x, jml=0, n=0;
        try
        {   FileReader fr = new FileReader(note);
            BufferedReader br = new BufferedReader(fr);
            while((str=br.readLine()) != null)
            {   x = Integer.parseInt(str);
                System.out.println(x);
                jml+=x;
                n++;
            }
            br.close();
        } catch(IOException e)
        {   System.err.println("File read error");
        }
        double rata = (double) jml/n;
        System.out.println("Jumlah : "+jml+"\nRata-rata : "+rata);
    }
}

versi sederhana
import java.io.*;
class TulisBacaFile
{   
   public static void main(String[] args)
    {   
       String str;
       FileWriter fw;
       BufferedWriter bw;
       try
       {    fw = new FileWriter("coba2.txt");
            bw = new BufferedWriter(fw);
            bw.write("baris kesatu"+"\r\n");
            bw.write("baris kedua"+"\r\n");
            bw.write("baris ketiga\r\n");
            bw.write("baris keempat\r\n");
            bw.flush();
            bw.close();
        } catch(IOException e)
        {   System.err.println("Kesalahan pada penulisan text ke File");
        }
       
       FileReader fr; 
       BufferedReader br;
       try
       {
            fr = new FileReader("coba2.txt");
            br = new BufferedReader(fr);
            while((str=br.readLine()) != null)
            {   
                System.out.println(str);
            }
            br.close();
        } catch(IOException e)
        {   System.err.println("Kesalahan pada pembacaan file text");
        }
    }
}
hasil yang tampil di layar:
baris kesatu
baris kedua
baris ketiga
baris keempat
Klik di sini untuk lihat PENJELASAN

Input dan Output ke text file part 1

Agar bebas dengan masalah lokasi file (file path), dibuat dua program. Yang kesatu adalah untuk menulis ke file dan yang kedua untuk menampilkan data dari file ke layar.

Program 1: Menulis string ke file

import java.io.*;
class TulisKeFile 
{	
public static void main(String args[])
{              
   FileOutputStream out; // declare a file output object
   PrintStream p; // declare a print stream object
   try
   {
     // Create a new file output stream
     // connected to "myfile.txt"
     out = new FileOutputStream("myfile.txt");

     // Connect print stream to the output stream
     p = new PrintStream( out );	
     p.println ("ini string yang ditulis ke file");
     p.close();
   }
   catch (Exception e)
   {
           System.err.println ("Error writing to file");
   }
   System.out.println("Tulis ke file OK");
}
}

kalau berhasil nulisnya, di layar akan tampil Tulis ke file OK
ada di mana file myfile.txt ? --> ada di folder yang sama dengan program
kalau dengan BlueJ ada di folder projectnya (bingung kan?)

Yang kedua, program untuk baca hasil program di atas

import java.io.*;

class BacaStringDariFile 
{
public static void main(String args[])
{ 
	try
	{
   FileInputStream fstream = new FileInputStream("myfile.txt");
   DataInputStream dataInput = new DataInputStream(fstream);
         
   while (dataInput.available() !=0)
	 {
		String data=dataInput.readLine();
	  System.out.println (data);
	 }
	 dataInput.close();
   }
   catch (Exception e)
   {
	 System.err.println("File input error");
}
}
}

Penjelasan untuk "hal-hal membingungkan" .....

  • import import java.io.*; maksudnya?
  • ..... dll ntar nyusul
  • ..... tanya azza soalnya kalau njelasin rada malez tapi kalau jawab pertanyaan semangat berkobar

Nambah sedikit lagi ..... kalau inputnya dibuat dengan NotePad, misalnya data harga buncis seminggu, lalu kita hitung rata-ratanya

Ketik data berikut dengan Notepad (ada 7 baris) save di c:\hargabuncis.txt


25
25
30
30
32
31
24

dan ini program untuk menampilkan harga buncis dan menghitung rata-rata harga buncisnya

import java.io.*;

class HargaBuncis 
{
public static void main(String args[])
{ 
   String x;
   int harga=0,jumlah=0,n=0; // cobain kalau int harga,jumlah,n;
   try
   {
   FileInputStream fstream = new FileInputStream("c:/hargabuncis.txt");
   DataInputStream dataInput = new DataInputStream(fstream);
         
   while (dataInput.available() !=0)
	 {
	  x=dataInput.readLine();
	  harga=Integer.parseInt(x);
	  n=n+1;
	  jumlah=jumlah+harga;
	  System.out.println ("Harga Buncis hari ke "+n+"  "+harga);
	 }
	 dataInput.close();
   }
   catch (Exception e)
   {
	 System.err.println("File input error");
   }
   double rata2=(double) jumlah/n;
   // cobain kalau pake double rata2=jumlah/n;  hasilnya spt apa?
   System.out.println ("Harga Buncis rata-rata "+rata2);
}
}

ini hasilnya

Harga Buncis hari ke 1  25
Harga Buncis hari ke 2  25
Harga Buncis hari ke 3  30
Harga Buncis hari ke 4  30
Harga Buncis hari ke 5  32
Harga Buncis hari ke 6  31
Harga Buncis hari ke 7  24
Harga Buncis rata-rata 28.142857142857142

koq desimalnya panjang amat? gimana supaya cuma 2 desimal? .... tunggu tgl mainnya!

sedikit penjelasan soal double rata2=(double) jumlah/n;

  • double rata2 deklarasi variabel rata2 dengan type double (krn rata-rata bisa bukan bilangan bulat)
  • (double) jumlah namanya type casting artinya konversikan jumlah menjadi type double
  • napa? >>>> soalnya kalau jumlah/n itu integer dibagi integer hasilnya integer juga; kalau jumlah misalnya 100 dan n 8 maka hasil ekspresi jumlah/n adalah 12 .. bukan 12.5 ........ understand?