Tags

, , ,

Ya nulis lagi… Oya gue sekarang lagi ngetes ubuntu 11.04 nih, hehe… Performanya lebih mantep dibanding OS gue yang satu lagi (Win**ws 7 Home Premium, walaupun punya gue ORI. hahaha)…

Okelah, kali ini gue mau kasih tau lu tentang kegunaan file properties java.util. Kelas ini berguna misalkan pas lu nyimpen settingan driver database supaya bisa di pake di semua kelas tanpa harus tulis ulang. Ya pokoknya gitu deh… Kita pake kelas java.util.properties, nantinya settingan ini bakalan kita export jadi file xml. Nah, file xml inilah yang bakalan nyimpen settingan kita… Simak nih source codenya…


Properties prop;
public void CreatePropertiesFile () {
        prop = new Properties();
        prop.setProperty("HOST", txtHost.getText());
        prop.setProperty("PORT", txtPort.getText());
        prop.setProperty("USER", txtUser.getText());
        prop.setProperty("PASS", String.copyValueOf(txtPass.getPassword(), 0, txtPass.getPassword().length));
        prop.setProperty("DB", txtDatabase.getText());

        FileOutputStream fos;
        try {
            fos = new FileOutputStream("setting.xml");
            prop.storeToXML(fos, "Settingan", "UTF-8");
            JOptionPane.showMessageDialog(this, "File Properties Successtifully Created!");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("Kacau ada Error di Filenya...");
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }
public void ReadPropertiesFile(){
        prop = new Properties();
        try {
            prop.loadFromXML(new FileInputStream("setting.xml"));
            JOptionPane.showMessageDialog(this, "Host : "+prop.getProperty("HOST")+
                    "\nPort : "+prop.getProperty("PORT")+
                    "\nUser : "+prop.getProperty("USER")+
                    "\nPass : "+prop.getProperty("PASS")+
                    "\nDB   : "+prop.getProperty("DB"));
        } catch (IOException ex) {
            Logger.getLogger(PropertiesFile.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Buat lu yang mau liat contoh programnya silahkan download di sini. Passwordnya : GanjarRamadhan

Oke… Sampai jumpa di tutorial selanjutnya…

Advertisements