- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package io;
- import java.io.DataInputStream;
- import java.io.FileInputStream;
- import java.io.DataOutputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- /**
- *
- * @author azlina
- */
- public class io {
- public static void main(String[] args) {
- //
- // Prepares some data to be written to a file.
- //
- int noA = 1;
- String name = "Azlina";
- try {
- //
- // Create an instance of FileOutputStream with cities.dat
- // as the file name to be created. Then we pass the input
- // stream object in the DataOutputStream constructor.
- //
- FileOutputStream fos = new FileOutputStream("cities.dat");
- DataOutputStream dos = new DataOutputStream(fos);
- //
- // Below we write some data to the cities.dat.
- // DataOutputStream class have various method that allow
- // us to write primitive type data and string. There are
- // method called writeInt(), writeFloat(), writeUTF(),
- // etc.
- //
- dos.writeInt(noA);
- dos.writeUTF(name);
- dos.flush();
- dos.close();
- //
- // Now we have a cities.dat file with some data in it.
- // Next you'll see how easily we can read back this
- // data and display it. Just like the DataOutputStream
- // the DataInputStream class have the corresponding
- // read methods to read data from the file. Some of
- // the method names are readInt(), readFloat(),
- // readUTF(), etc.
- //
- FileInputStream fis = new FileInputStream("cities.dat");
- DataInputStream dis = new DataInputStream(fis);
- //
- // Read the first data
- //
- int no1 = dis.readInt();
- int results;
- results=no1+2;
- System.out.println("Results: " + results);
- String name1 = dis.readUTF();
- System.out.println("Name: " + name1);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }