data input stream

Upload: taqi-hassan

Post on 08-Apr-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Data Input Stream

    1/34

    1 | P a g e

    DatainputStreamy R ead boolean from file using DataInputStreamy R ead byte array from file using DataInputStreamy R ead byte from file using DataInputStreamy R ead char from file using DataInputStreamy R ead double from file using DataInputStreamy

    R ead float from file using DataInputStreamy R ead int from file using DataInputStreamy R ead long from file using DataInputStreamy R ead short from file using DataInputStreamy R ead unsigned byte from file using DataInputStream

    1. Read bool ean from fil e using DataInp utSt rea m

    /* R ead boolean from file using DataInputStream This Java example shows how to read a Java boolean primitive value from file using

    readBoolean method of Java DataInputStream class. */

    import java.io.DataInputStream; import java.io.FileInputStream;

    import java.io.FileNotFoundException; import java.io.IOException;

    public class R eadBooleanFromFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//readBoolean.txt";

    try{//create FileInputStream objectFileInputStream fin = new FileInputStream(strFilePath);

    /* * To create DataInputStream object, use * DataInputStream(InputStream in) constructor. */

    DataInputStream din = new DataInputStream(fin);

    /* * To read a Java boolean primitive from file, use * byte readBoolean() method of Java DataInputStream class.* This method reads one byte from file and returns true if byte is nonzero, * false if the byte is zero. */

    boolean b = din.readBoolean();

    System.out.println("boolean : " + b);

    /* * To close DataInputStream, use * void close() method. */din.close();

    }catch(FileNotFoundException fe){System.out.println("FileNotFoundException : " + fe);

    }catch(IOException ioe){System.out.println("IOException : " + ioe);

  • 8/6/2019 Data Input Stream

    2/34

    2 | P a g e

    }}

    }

    2 . Read by te a rra y from fil e using DataInp u tSt rea m

    /* R ead byte array from file using DataInputStream This Java example shows how to read an array of bytes from file usingread or readFully method of Java DataInputStream class. */

    import java.io.DataInputStream; import java.io.FileInputStream;

    import java.io.FileNotFoundException; import java.io.IOException;

    public class R eadByteArrayFromFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//readByteArray.txt";

    try{//create FileInputStream objectFileInputStream fin = new FileInputStream(strFilePath);

    /* * To create DataInputStream object, use * DataInputStream(InputStream in) constructor. */

    DataInputStream din = new DataInputStream(fin);

    /* * To read an array of bytes from file, use * int read(byte b[]) method of Java DataInputStream class.* This method reads bytes from input stream and store them in array of bytes. * It returns number of bytes read. */

    byte b[] = new byte[10];din.read(b);

    /* * To close DataInputStream, use * void close() method. */din.close();

    }catch(FileNotFoundException fe)

    {System.out.println("FileNotFoundException : " + fe);

    }catch(IOException ioe){System.out.println("IOException : " + ioe);

    }}

    }

    3 . Read by te from fil e using DataInp utSt rea m

    /* R ead byte from file using DataInputStream This Java example shows how to read a Java byte primitive value from file using readByte method of Java DataInputStream class. */

    import java.io.DataInputStream; import java.io.FileInputStream;import java.io.FileNotFoundException; import java.io.IOException;

    public class R eadByteFromFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//readByte.txt";

    try

  • 8/6/2019 Data Input Stream

    3/34

    3 | P a g e

    {//create FileInputStream objectFileInputStream fin = new FileInputStream(strFilePath);

    /* * To create DataInputStream object, use * DataInputStream(InputStream in) constructor. */

    DataInputStream din = new DataInputStream(fin);

    /* * To read a Java byte primitive from file, use * byte readByte() method of Java DataInputStream class. */

    byte b = din.readByte();

    System.out.println("byte : " + b);

    /* * To close DataInputStream, use * void close() method. */din.close();

    }catch(FileNotFoundException fe){System.out.println("FileNotFoundException : " + fe);

    }catch(IOException ioe){

    System.out.println("IOException : " + ioe);}

    }}

    4. Read cha r from fil e using DataInp utSt rea m

    /* R ead char from file using DataInputStream This Java example shows how to read a Java char primitive value from file using readChar methodof Java DataInputStream class. */

    import java.io.DataInputStream; import java.io.FileInputStream;import java.io.FileNotFoundException; import java.io.IOException;

    public class R eadCharFromFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//readChar.txt";

    try{//create FileInputStream objectFileInputStream fin = new FileInputStream(strFilePath);

    /* * To create DataInputStream object, use * DataInputStream(InputStream in) constructor. */

    DataInputStream din = new DataInputStream(fin);

    /* * To read a Java character primitive from file, use * byte readChar() method of Java DataInputStream class.* This method reads 2 bytes and returns unicode char value(Unicode char * occupies 2 bytes). */

    char ch = din.readChar();

    System.out.println("Char : " + ch);

    /* * To close DataInputStream, use * void close() method. */din.close();

    }

  • 8/6/2019 Data Input Stream

    4/34

    4 | P a g e

    catch(FileNotFoundException fe){System.out.println("FileNotFoundException : " + fe);

    }catch(IOException ioe){System.out.println("IOException : " + ioe);

    }}

    }

    5. Read doubl e from fil e using DataInp u tSt rea m

    /* Read double from file using DataInputStream This Java example shows how to read a Java double primitive value from file using readDoublemethod of Java DataInputStream class. */

    import java.io.DataInputStream;, import java.io.FileInputStream;import java.io.FileNotFoundException; import java.io.IOException;

    public class R eadDoubleFromFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//readDouble.txt";

    Try {//create FileInputStream objectFileInputStream fin = new FileInputStream(strFilePath);

    /* * To create DataInputStream object, use * DataInputStream(InputStream in) constructor. */

    DataInputStream din = new DataInputStream(fin);

    /* * To read a Java double primitive from file, use * byte readDouble() method of Java DataInputStream class.* * This method reads 8 bytes and returns it as a double value. */

    double d = din.readDouble();

    System.out.println("Double : " + d);

    /* * To close DataInputStream, use * void close() method. */din.close();

    }catch(FileNotFoundException fe){System.out.println("FileNotFoundException : " + fe);

    }catch(IOException ioe){System.out.println("IOException : " + ioe);

    }}

    }

    6. Read float from fil e using DataInp u tSt rea m

    /* R ead float from file using DataInputStream This Java example shows how to read a Java float primitive value from file using readFloatmethod of Java DataInputStream class. */

    import java.io.DataInputStream; import java.io.FileInputStream;import java.io.FileNotFoundException; import java.io.IOException;

  • 8/6/2019 Data Input Stream

    5/34

    5 | P a g e

    public class R eadFloatFromFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//readFloat.txt";

    try{//create FileInputStream objectFileInputStream fin = new FileInputStream(strFilePath);

    /* * To create DataInputStream object, use * DataInputStream(InputStream in) constructor. */

    DataInputStream din = new DataInputStream(fin);

    /* * To read a Java float primitive from file, use * byte readFloat() method of Java DataInputStream class.* * This method reads 4 bytes and returns it as a float value.*/

    float f = din.readFloat();

    System.out.println("float : " + f);

    /* * To close DataInputStream, use * void close() method. */din.close();

    }catch(FileNotFoundException fe){System.out.println("FileNotFoundException : " + fe);

    }catch(IOException ioe){System.out.println("IOException : " + ioe);

    }}

    }

    7. Read int from fil e using DataInp utSt rea m

    *R ead int from file using DataInputStreamThis Java example shows how to read a Java integer primitive value from file usingreadInt method of Java DataInputStream class.*/

    import java.io.DataInputStream; import java.io.FileInputStream;import java.io.FileNotFoundException; import java.io.IOException;

    public class R eadIntFromFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//readInt.txt";

    try{//create FileInputStream objectFileInputStream fin = new FileInputStream(strFilePath);

    /* * To create DataInputStream object, use * DataInputStream(InputStream in) constructor. */

    DataInputStream din = new DataInputStream(fin);

    /* * To read a Java integer primitive from file, use * byte readInt() method of Java DataInputStream class.* * This method reads 4 bytes and returns it as a int value. */

    int i = din.readInt();

  • 8/6/2019 Data Input Stream

    6/34

    6 | P a g e

    System.out.println("int : " + i);

    /* * To close DataInputStream, use * void close() method. */din.close();

    }catch(FileNotFoundException fe){System.out.println("FileNotFoundException : " + fe);

    }catch(IOException ioe){System.out.println("IOException : " + ioe);

    }}

    }

    8. Read long from fil e using DataInp utSt rea m

    /* R ead long from file using DataInputStream This Java example shows how to read a Java long primitive value from file usingreadLong method of Java DataInputStream class. */

    import java.io.DataInputStream; import java.io.FileInputStream;

    import java.io.FileNotFoundException; import java.io.IOException;

    public class R eadLongFromFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//readLong.txt";

    try{//create FileInputStream objectFileInputStream fin = new FileInputStream(strFilePath);

    /* * To create DataInputStream object, use * DataInputStream(InputStream in) constructor. */

    DataInputStream din = new DataInputStream(fin);

    /* * To read a Java long primitive from file, use * byte readLong() method of Java DataInputStream class. * This method reads 8 bytes andreturns it as a long value. */

    long l = din.readLong();

    System.out.println("long : " + l);

    /* * To close DataInputStream, use * void close() method. */din.close();

    }catch(FileNotFoundException fe){System.out.println("FileNotFoundException : " + fe);

    }catch(IOException ioe){System.out.println("IOException : " + ioe);

    }}

    }

  • 8/6/2019 Data Input Stream

    7/34

    7 | P a g e

    9. Read shor t from fil e using DataInp utSt rea m/* R ead short from file using DataInputStream This Java example shows how to read a Java short primitive value from file usingreadShort method of Java DataInputStream class. */

    import java.io.DataInputStream; import java.io.FileInputStream;import java.io.FileNotFoundException; import java.io.IOException;

    public class R eadShortFromFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//readShort.txt";

    try{//create FileInputStream objectFileInputStream fin = new FileInputStream(strFilePath);

    /* * To create DataInputStream object, use * DataInputStream(InputStream in) constructor. */

    DataInputStream din = new DataInputStream(fin);

    /* * To read a Java short primitive from file, use * byte readShort() method of Java DataInputStream class.

    * This method reads 2 bytes and returns it as a short value. */

    short s = din.readShort();

    System.out.println("short : " + s);

    /* * To close DataInputStream, use * void close() method. */din.close();

    }catch(FileNotFoundException fe){System.out.println("FileNotFoundException : " + fe);

    }

    catch(IOException ioe){System.out.println("IOException : " + ioe);

    }}

    }

    10. Read unsigned by te from fil e using DataInp utSt rea m/* R ead unsigned byte from file using DataInputStream This Java example shows how to read an unsigned byte value from file using

    readUnsignedByte method of Java DataInputStream class. */

    import java.io.DataInputStream; import java.io.FileInputStream;import java.io.FileNotFoundException; import java.io.IOException;

    public class R eadUnsignedByteFromFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//readUnsignedByte.txt";

    try{//create FileInputStream objectFileInputStream fin = new FileInputStream(strFilePath);

    /* * To create DataInputStream object, use * DataInputStream(InputStream in) constructor. */

  • 8/6/2019 Data Input Stream

    8/34

    8 | P a g e

    DataInputStream din = new DataInputStream(fin);

    /* * To read an unsigned byte value from file, use * int readUnsignedByte() method of Java DataInputStream class.* This value ranges from 0 to 255. */

    int i = din.readUnsignedByte();

    System.out.println("Unsinged byte value : " + i);

    /* * To close DataInputStream, use * void close() method. */din.close();

    }catch(FileNotFoundException fe){System.out.println("FileNotFoundException : " + fe);

    }catch(IOException ioe){System.out.println("IOException : " + ioe);

    }}

    }

    DataOutputStream

    y Create DataOutputStream from FileOutputStreamy Determine number of bytes written to DataOutputStreamy Flush output streamy W rite boolean to a file using DataOutputStreamy W rite byte to a file using DataOutputStreamy W rite char to a file using DataOutputStreamy W rite double to a file using DataOutputStreamy W rite float to a file using DataOutputStreamy W rite int to a file using DataOutputStreamy W rite long to a file using DataOutputStreamy W rite short to a file using DataOutputStreamy W rite String as bytes to a file using DataOutputStreamy W rite String as characters to a file using DataOutputStream

    1. Create DataO u tp utSt rea m from Fil eO u tp u tSt rea m

    /* Create DataOutputStream from FileOutputStream This Java example shows how to create DataOutputStream from FileOutputStream object.*/

    import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream;

    public class CreateDataOutputStream {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//demo.txt";

    try{//create FileOutputStream objectFileOutputStream fos = new FileOutputStream(strFilePath);

    /* * To create DataOutputStream object from FileOutputStream use, * DataOutputStream(OutputStream os) constructor. */

  • 8/6/2019 Data Input Stream

    9/34

    9 | P a g e

    DataOutputStream dos = new DataOutputStream(fos);}catch(FileNotFoundException fe){System.out.println("FileNotFoundException : " + fe);

    }}

    }

    2 . Dete rmi ne numb e r of by te s wri tten to DataO utp u tSt rea m

    /* Determine number of bytes written to DataOutputStream This Java example shows how to determine total number of bytes written tothe output stream using size method of DataOutputStream class. */

    import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

    public class NumberOfBytes W ritten {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//NumberOfBytes.txt";

    try

    {//create FileOutputStream objectFileOutputStream fos = new FileOutputStream(strFilePath);

    /* * To create DataOutputStream object from FileOutputStream use, * DataOutputStream(OutputStream os) constructor. */

    DataOutputStream dos = new DataOutputStream(fos);

    String str = "Example to show number of bytes written to stream";dos.writeBytes(str);

    /* * To determine total number of bytes written to underlying stream, use * int size() method.*/

    int bytes W ritten = dos.size();

    System.out.println("Total " + bytes W ritten + " bytes are written to stream.");

    dos.close();

    }catch (IOException e){System.out.println("IOException : " + e);

    }}}

    3 . Flush ou tp u t st rea m/* Flush output stream This Java example shows how to flush output stream using flush method of DataOutputStream class. */

    import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

    public class FlushStream {

    public static void main(String[] args) {String strFilePath = "C://FileIO// W riteByte.txt";

    try{//create FileOutputStream object

  • 8/6/2019 Data Input Stream

    10/34

    10 | P a g e

    FileOutputStream fos = new FileOutputStream(strFilePath);

    /* * To create DataOutputStream object from FileOutputStream use, * DataOutputStream(OutputStream os) constructor. */

    DataOutputStream dos = new DataOutputStream(fos);

    String strContent = "This example shows how to flush output stream!";dos.writeBytes(strContent);

    /* * To flush output stream, use * void flush() method of DataOutputStream class. * This method internally calls flush method of

    underlying OutputStream * class which forces any buffered output bytes to be written in the stream. */

    dos.flush();

    //close the streamdos.close();

    }catch (IOException e){System.out.println("IOException : " + e);

    }}

    }

    4. W rite bool ean to a file using DataO utp utSt rea m/* W rite boolean to a file using DataOutputStream This Java example shows how to write a Java boolean primitive value to a file using

    writeBoolean method of Java DataOutputStream class. */

    import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

    public class W riteBooleanToFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO// W riteBoolean.txt";

    try

    {//create FileOutputStream objectFileOutputStream fos = new FileOutputStream(strFilePath);

    /* * To create DataOutputStream object from FileOutputStream use, * DataOutputStream(OutputStream os) constructor. */

    DataOutputStream dos = new DataOutputStream(fos);

    boolean b = false;

    /* * To write a boolean value to a file, use * void writeBoolean(boolean b) method of Java DataOutputStream class. * This method writesspecified boolean to output stream as a 1 byte (true * value is written out as 1 whereas false as 0) */

    dos.writeBoolean(b);

    /* * To close DataOutputStream use, * void close() method. */

    dos.close();}catch (IOException e){System.out.println("IOException : " + e);

    }}

    }

  • 8/6/2019 Data Input Stream

    11/34

    11 | P a g e

    5. W rite by te to a file using DataO u tp utSt rea m/* W rite byte to a file using DataOutputStream This Java example shows how to write a Java byte primitive value to a file using writeBytemethod of Java DataOutputStream class. */

    import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

    public class W riteByteToFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO// W riteByte.txt";

    try{//create FileOutputStream objectFileOutputStream fos = new FileOutputStream(strFilePath);

    /* * To create DataOutputStream object from FileOutputStream use, * DataOutputStream(OutputStream os) constructor. */

    DataOutputStream dos = new DataOutputStream(fos);

    int i = 1;

    /* * To write a byte value to a file, use * void writeByte(int i) method of Java DataOutputStream class. * This method writes specified byte to

    output stream as a 1 byte. */

    dos.writeByte(i);

    /* * To close DataOutputStream use, * void close() method. */

    dos.close();}

    catch (IOException e){System.out.println("IOException : " + e);

    }

    }

    }

    6. W rite cha r to a file using DataO utp u tSt rea m/* W rite char to a file using DataOutputStream This Java example shows how to write a Java character primitive value to afile using writeChar method of Java DataOutputStream class. */

    import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

    public class W riteCharToFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO// W riteChar.txt";

    try{//create FileOutputStream objectFileOutputStream fos = new FileOutputStream(strFilePath);

    /* * To create DataOutputStream object from FileOutputStream use, * DataOutputStream(OutputStream os) constructor. */

    DataOutputStream dos = new DataOutputStream(fos);

    int ch = 65;

  • 8/6/2019 Data Input Stream

    12/34

    12 | P a g e

    /* * To write a char value to a file, use * void writeChar(int ch) method of Java DataOutputStream class. * This method writes specified charto output stream as 2 bytes value.*/

    dos.writeChar(ch);

    /* * To close DataOutputStream use, * void close() method. */

    dos.close();

    }

    catch (IOException e){System.out.println("IOException : " + e);

    }}

    }

    7. W rite doubl e to a file using DataO u tp utSt rea m/* W rite double to a file using DataOutputStream This Java example shows how to write a Java double primitive value to a file using

    writeDouble method of Java DataOutputStream class. */

    import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

    public class W riteDoubleToFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO// W riteDouble.txt";

    try{//create FileOutputStream objectFileOutputStream fos = new FileOutputStream(strFilePath);

    /* * To create DataOutputStream object from FileOutputStream use, * DataOutputStream(OutputStream os) constructor. */

    DataOutputStream dos = new DataOutputStream(fos);

    double d = 165;

    /* * To write a double value to a file, use * void writeDouble(double d) method of Java DataOutputStream class.* This method writes specified double to output stream as 8 bytes value. * Please note that the double value is first converted to long using

    * Double.doubleToLongBits method and then long is written to * underlying output stream. */

    dos.writeDouble(d);

    /* * To close DataOutputStream use, * void close() method. */

    dos.close();

    }catch (IOException e){System.out.println("IOException : " + e);

    }}

    }

    8. W rite float to a file using DataO utp u tSt rea m

    y W rite float to a file using DataOutputStream This Java example shows how to write a Java float primitive value to a file usingwriteFloat method of Java DataOutputStream class. */

    import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

  • 8/6/2019 Data Input Stream

    13/34

    13 | P a g e

    public class W riteFloatToFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO// W riteFloat.txt";

    try{//create FileOutputStream object

    FileOutputStream fos = new FileOutputStream(strFilePath);

    /* To create DataOutputStream object from FileOutputStream use, DataOutputStream(OutputStream os) constructor. */

    DataOutputStream dos = new DataOutputStream(fos);

    float f = 5.314f;

    /* To write a float value to a file, use void writeFloat(float f) method of Java DataOutputStream class. This method writes specified float tooutput stream as 4 bytes value. Please note that the float value is first converted to int using Float.floatToIntBits method and then int is written tounderlying output stream. */

    dos.writeFloat(f);

    /* To close DataOutputStream use, void close() method. */

    dos.close();

    }catch (IOException e){System.out.println("IOException : " + e);

    }

    }}

    9. W rite int to a file using DataO utp u tSt rea m/* W rite int to a file using DataOutputStream This Java example shows how to write a Java integer primitive value to a file using

    writeInt method of Java DataOutputStream class. */

    import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

    public class W riteIntToFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO// W riteInt.txt";

    try{//create FileOutputStream objectFileOutputStream fos = new FileOutputStream(strFilePath);

    /* * To create DataOutputStream object from FileOutputStream use, * DataOutputStream(OutputStream os) constructor. */

    DataOutputStream dos = new DataOutputStream(fos);

    int i = 100;

    /* * To write an int value to a file, use * void writeInt(int i) method of Java DataOutputStream class. This method writes specified int tooutput stream as 4 bytes value. */

    dos.writeInt(i);

  • 8/6/2019 Data Input Stream

    14/34

    14 | P a g e

    /* * To close DataOutputStream use, * void close() method. */

    dos.close();

    }catch (IOException e){System.out.println("IOException : " + e);

    }

    }}

    10. W rite long to a file using DataO utp u tSt rea m/* W rite long to a file using DataOutputStream This Java example shows how to write a Java long primitive value to a file using

    writeLong method of Java DataOutputStream class. */

    import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

    public class W riteLongToFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO// W riteLong.txt";

    try{//create FileOutputStream objectFileOutputStream fos = new FileOutputStream(strFilePath);

    /* * To create DataOutputStream object from FileOutputStream use, * DataOutputStream(OutputStream os) constructor. */

    DataOutputStream dos = new DataOutputStream(fos);

    long l = 65;

    /* * To write a long value to a file, use * void writeLong(long l) method of Java DataOutputStream class.

    * This method writes specified long to output stream as 8 bytes value. */

    dos.writeLong(l);

    /* * To close DataOutputStream use, * void close() method. */

    dos.close();

    }catch (IOException e){System.out.println("IOException : " + e);

    }}

    }

    11. W rite shor t to a file using DataO u tp u tSt rea m/* W rite short to a file using DataOutputStream This Java example shows how to write a Java short primitive value to a file using

    writeShort method of Java DataOutputStream class. */

    import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

    public class W riteShortToFile {

    public static void main(String[] args) {

  • 8/6/2019 Data Input Stream

    15/34

    15 | P a g e

    String strFilePath = "C://FileIO// W riteShort.txt";

    try{//create FileOutputStream objectFileOutputStream fos = new FileOutputStream(strFilePath);

    /* * To create DataOutputStream object from FileOutputStream use, * DataOutputStream(OutputStream os) constructor. */

    DataOutputStream dos = new DataOutputStream(fos);

    short s = 1;

    /* * To write a short value to a file, use * void writeShort(short s) method of Java DataOutputStream class.* This method writes specified short to output stream as 2 bytes value. */

    dos.writeShort(s);

    /** To close DataOutputStream use, * void close() method. */

    dos.close();

    }catch (IOException e)

    {System.out.println("IOException : " + e);

    }}

    }

    12 . W rite String a s by te s to a file using DataO utp utSt rea m/* W rite String as bytes to a file using DataOutputStream This Java example shows how to write a Java String value to a file

    as a sequence of bytes using writeBytes method of Java DataOutputStream class. */

    import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

    public class W riteStringAsBytesToFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO// W riteStringAsBytes.txt";

    try{//create FileOutputStream objectFileOutputStream fos = new FileOutputStream(strFilePath);

    /* * To create DataOutputStream object from FileOutputStream use, * DataOutputStream(OutputStream os) constructor. */

    DataOutputStream dos = new DataOutputStream(fos);

    String str = "This string will be written to file as sequence of bytes!";

    /* * To write a string as a sequence of bytes to a file, use * void writeBytes(String str) method of Java DataOutputStream class.* This method writes string as a sequence of bytes to underlying output * stream (Each character's high eight bits are discarded first). */

    dos.writeBytes(str);

    /* * To close DataOutputStream use, * void close() method. */

    dos.close();}catch (IOException e){

  • 8/6/2019 Data Input Stream

    16/34

    16 | P a g e

    System.out.println("IOException : " + e);} } }

    13 . W rite String a s cha racte rs to a file using DataO utp utSt rea m

    /* W rite String as characters to a file using DataOutputStreamn This Java example shows how to write a Java String value to a file as a sequenceof characters using writeChars method of Java DataOutputStream class. */

    import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

    public class W riteStringAsCharsToFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO// W riteStringAsChars.txt";

    try{//create FileOutputStream objectFileOutputStream fos = new FileOutputStream(strFilePath);

    /* * To create DataOutputStream object from FileOutputStream use, * DataOutputStream(OutputStream os) constructor. */

    DataOutputStream dos = new DataOutputStream(fos);

    String str = "This string will be written to file as sequence of characters!";

    /* * To write a string as a sequence of characters to a file, use * void writeChars(String str) method of Java DataOutputStream class.* This method writes string as a sequence of characters to underlying output stream. */

    dos.writeChars(str);

    /* * To close DataOutputStream use, * void close() method. */

    dos.close();

    }

    catch (IOException e){System.out.println("IOException : " + e);

    }}}

    F ile And Directory

    y Compare two file pathsy Construct file pathy Create directory

  • 8/6/2019 Data Input Stream

    17/34

    17 | P a g e

    y Create directory along with required nonexistent parent directoriesy Create new empty filey Create temporary filey Create temporary file in specified directoryy Delete file or directoryy Delete file or directory when virtual machine terminatesy Determine File or Directoryy Determine if a file can be ready Determine if a file can be writteny Determine if file or directory existsy Determine if File or Directory is hiddeny G et Absoulte path of the filey G et File size in bytesy G et Last modification time of a file or directoryy G et name of parent directoryy G et name of specified file or directoryy G et parent directory as a File objecty List contents of a directoryy List Filesystem rootsy M ark file or directory Read Onlyy R ename file or directoryy Set last modified time of a file or directory

    1. Com pa re two fil e pat hs/* Compare two file paths This Java example shows how to compare two file paths using compareTo method of Java File class. */

    import java.io.*;public class CompareTwoFilePaths {

    public static void main(String[] args) {//create first file objectFile file1 = new File("C://FileIO//demo1.txt");

    //create second file objectFile file2 = new File("C://FileIO//demo1.txt");

    /* * To compare file paths use, * int compareTo(File file) method of Java File class. * This method returns 0 of both paths are same, integer less

    than 0 if * file path is less than that of argument, and positive integer if the * file path is grater than that of argument. */

    if(file1.compareTo(file2) == 0){System.out.println("Both paths are same!");

    }else{System.out.println("Paths are not same!");

    }}

    }

    2 . Const ruc t file pat h/* Construct file path This Java example shows how to construct a file path in Java using File class. */

    import java.io.*;public class ConstructFilePath {

    public static void main(String[] args) {

    /* * To create a file path use File.separator constant defined in * File class. * W indows based machines has path like \dir1\dir2 while UNIXbased machines * has path like /dir1/dir2 */

    String filePath = File.separator + "JavaExamples" + File.separator + "IO";

    //create new File object

  • 8/6/2019 Data Input Stream

    18/34

    18 | P a g e

    File file = new File(filePath);

    /* * Please note that creating file object DOES NOT actually create a file. * It DOES NOT have any effects on the filesystem. */

    //display file path using getPath() method of File class.System.out.println("File path is : " + file.getPath());

    }}

    /*Output in W indows machine would be,File path is : \JavaExamples\IO

    Output in UNIX machine would be,File path is : /JavaExamples/IO*/

    3 . Create d ire ctory/* Create directory This Java example shows how to create a directory in the filesystem using mkdir method of Java File class. */

    import java.io.*;public class CreateDirectory {

    public static void main(String[] args) {//create file objectFile dir = new File("C://FileIO//DemoDirectory");

    /* * To create directory in the filesystem use, * boolean mkdir() method of Java File class. * This method returns true if the directory wascreated successfully, false * otherwise. */

    boolean isDirectoryCreated = dir.mkdir();

    if(isDirectoryCreated)System.out.println("Directory created successfully");

    elseSystem.out.println("Directory was not created successfully");

    }

    }

    /*Output would beDirectory created successfully*/

    4. Create d ire ctory a long with r eq uir ed nonex istent pa rent d irectorie s/* Create directory along with required nonexistent parent directories This Java example shows how to create a directory along with the requiredparent directories in the filesystem using mkdirs method of Java File class. */

    import java.io.*;public class CreateDirParentDir {

    public static void main(String[] args) {

    //create File objectFile dir = new File("C://FileIO//Parent1//Parent2//DemoDir");

    /* * To create directory along with the required nonexistent parent directories use, * boolean mkdirs() method of Java File class. * This methodreturns true if the directory was created successfully along with * all necessary nonexistent parent directories, false otherwise.

    ** It may be possible that, some of the parent directories may have been created * eventhough the operation fails. */

    boolean isDirCreated = dir.mkdirs();

    if(isDirCreated)

  • 8/6/2019 Data Input Stream

    19/34

    19 | P a g e

    System.out.println("Directory created along with required nonexistentparent directories");

    elseSystem.out.println("Failed to create directory");

    }}

    /*Output would beDirectory created along with required nonexistent parent directories

    */

    5. Create ne w em pt y file /* Create new empty file This Java example shows how to create new empty file at specified path using createNewFile method of Java File class.*/

    import java.io.*;public class CreateNewEmptyFile {

    public static void main(String[] args) {//create File objectFile file = new File("C://demo.txt");

    /* * To actually create a file specified by a pathname, use * boolean createNewFile() method of Java File class. * This method creates a newempty file specified if the file with same * name does not exists. * This method returns true if the file with the same name did not exist and

    * it was created successfully, false otherwise. */

    boolean blnCreated = false;try{blnCreated = file.createNewFile();

    }catch(IOException ioe){System.out.println("Error while creating a new empty file :" + ioe);

    }

    System.out.println(" W as file " + file.getPath() + " created ? : " + blnCreated);

    /* * If you run the same program 2 times, first time it should return true. * But when we run it second time, it returns false because file wasalready * exist. */

    }}

    /*Output would beW as file C:\demo.txt created ? : true*/

    6. Create te m por a ry file /* Create temporary file This Java example shows how to create a new temporary file using createTempFile method of Java File class. */

    import java.io.*;public class CreateTemporaryFile {

    public static void main(String[] args) {/* * To create temporary file use, * static File createTempFile(String namePrefix, String nameSuffix) method of Java File class, where

    namePrefix is a prefix string used to generate a file's name and must be atleast 3 characters long and nameSuffix is a suffix string used to generatesuffix of the temporary file name. Suffix may be null, and in that case default ".tmp" will be used as a suffix. */

    File file1 = null;File file2 = null;

    try{

  • 8/6/2019 Data Input Stream

    20/34

    2 0 | P a g e

    //create temporary file wihtout extension suffixfile1 = File.createTempFile("JavaTemp", null);

    //create temporary file with specified extension suffixfile2 = File.createTempFile("JavaTemp", ".javatemp");

    }catch(IOException ioe){System.out.println("Exception creating temporary file : " + ioe);

    }

    /* Temporary file will be created in default temporary directory of operating system. */System.out.println("Temporary file without suffix extension: " + file1.getPath());System.out.println("Temporary file with suffix extension: " + file2.getPath());

    }}

    /* Typical output would beTemporary file without suffix extension: C:\Temp\JavaTemp45096.tmpTemporary file with suffix extension: C:\Temp\JavaTemp45097.javatemp*/

    7. Create te m por a ry file in spe cified d ire ctory/* Create temporary file in specified directory This Java example shows how to create a new temporary file at specified path using

    createTempFile method of Java File class. */

    import java.io.*;public class CreateTempFileDirectory {

    public static void main(String[] args) {

    /* To create temporary file at specified location use, static File createTempFile(String namePrefix, String nameSuffix, File dir) method of Java Fileclass, where namePrefix is a prefix string used to generate a file's name and must be atleast 3 characters long and nameSuffix is a suffix string usedto generate suffix of the temporary file name, may be null, and in that case default ".tmp" will be used as a suffix. dir is the directory under whichthe temporary file will be created. */

    File file = null;

    File dir = new File("C://FileIO");

    try{file = File.createTempFile("JavaTemp", ".javatemp", dir);

    }catch(IOException ioe){System.out.println("Exception creating temporary file : " + ioe);}

    /* Please note that if the directory does not exists, IOException will be thrown and temporary file will not be created. */System.out.println("Temporary file created at : " + file.getPath());

    }}

    /* Typical output would beTemporary file created at : C:\FileIO\JavaTemp40534.javatemp*/

    8. De lete file or d ire ctory/* Delete file or directory This Java example shows how to delete a particular file or directory from filesystem using delete method of Java Fileclass. */

    import java.io.*;

  • 8/6/2019 Data Input Stream

    21/34

    2 1 | P a g e

    public class DeleteFileOrDirectory {public static void main(String[] args) {//create file objectFile file = new File("C://FileIO/DeleteDemo.txt");

    /* To delete a file or directory from filesystem, use boolean delete() method of File class. This method returns true if file or directory successfullydeleted. If the file is a directory, it must be empty. */

    boolean blnDeleted = file.delete();System.out.println(" W as file deleted ? : " + blnDeleted);

    /* Please note that delete method returns false if the file did not exists or the directory was not empty. */}

    }

    /* Output would beW as file deleted ? : true*/

    9. De lete file or d ire ctory wh en virtua l machine te rmi nate s/* Delete file or directory when virtual machine terminates This Java example shows how to delete a particular file or directory from filesystemwhen Java Virtual M achine terminates using deleteOnExit method of Java File class */

    import java.io.*;

    public class DeleteFile W henV M Terminates {public static void main(String[] args) {//create File objectFile file = new File("C://FileIO//DeleteDemo.txt");

    /* To delete a particular file or directory when Java V M exits, use void deleteOnExit() method. This method request to delete a specified file ordirectory to be deleted when virtual machine terminates normally. */

    file.deleteOnExit();

    /* Please note that, once deletion has been requested, it is not possible to cancel that operation. */}

    }

    10. Dete rmi ne File or Dir e ctory/* Determine if it's a File or Directory This Java example shows how to determine if a particular file object denotes a file or directory of filesystemusing isFile and isDirectory methods of Java File class. */

    import java.io.*;public class DetermineDirOrFile {

    public static void main(String[] args) {//create file objectFile file = new File("C://FileIO");

    /* To check whether File object denotes a file or not, use boolean isFile() method of Java File class. This method returns true if the file EXISTS andits a normal file. */

    boolean isFile = file.isFile();if(isFile)System.out.println(file.getPath() + " is a file.");

    elseSystem.out.println(file.getPath() + " is not a file.");

    /* To check whether File object denotes a directory or not, use boolean isDirectory() method of Java File class. This method returns true if thedirectory EXISTS and its a directory. */

    boolean isDirectory = file.isDirectory();if(isDirectory)System.out.println(file.getPath() + " is a directory.");

    else

  • 8/6/2019 Data Input Stream

    22/34

    22 | P a g e

    System.out.println(file.getPath() + " is not a directory.");

    }}

    /* Output would beC:\FileIO is not a file.C:\FileIO is a directory.*/

    11. Dete rmi ne if a file can be read y Determine if a file can be read This Java example shows how to determine if a particular file has a read permission using can R ead

    method of Java File class. */

    import java.io.*;public class Determine R eadFile {

    public static void main(String[] args) {

    //create file pathString filePath = "C:/FileIO/ R eadText.txt";

    //create File objectFile file = new File(filePath);

    /* To determine whether a particular file can be read use, boolean can R ead() method of Java File class. This method returns true IF AND ONLY IFthe file exists and it can be read (file has a read permission). */

    if(file.can R ead()){System.out.println("File " + file.getPath() +" can be read");

    }else{System.out.println("File " + file.getPath() +" can not be read");

    }}

    }

    /* Output would beFile C:\FileIO\ R eadText.txt can be read*/

    12 . Dete rmi ne if a file can be wri tten /* Determine if a file can be written This Java example shows how to determine if a particular file has a write permission using can W rite methodof Java File class. */

    import java.io.*;public class Determine W riteFile {

    public static void main(String[] args) {//create file pathString filePath = "C:/FileIO/ R eadText.txt";

    //create File objectFile file = new File(filePath);

    /* To determine whether a particular file can be written use, boolean can W rite() method of Java File class. This method returns true IF AND ONLYIF the file exists and it can be written (file has a write permission). */

    if(file.can W rite()){System.out.println("File " + file.getPath() +" can be written");

    }else{

  • 8/6/2019 Data Input Stream

    23/34

    23 | P a g e

    System.out.println("File " + file.getPath() +" can not be written");}

    }}

    /* Output would beFile C:\FileIO\ R eadText.txt can be written*/

    13 . Dete rmi ne if file or d irectory ex ists

    /* Determine if file or directory exists This Java example shows how to determine if a particular file or directory exists in the filesystem using existsmethod of Java File class. */

    import java.io.*;public class DetermineIfFileExists {

    public static void main(String[] args) {

    //create file objectFile file = new File("C://FileIO/ExistsDemo.txt");

    /* To determine whether specified file or directory exists, use boolean exists() method of Java File class. This method returns true if a particularfile or directory exists at specified path in the filesystem, false otherwise. */

    boolean blnExists = file.exists();System.out.println("Does file " + file.getPath() + " exist ?: " + blnExists);

    }}

    /*Output would beDoes file C:\FileIO\ExistsDemo.txt exist ?: true*/

    14. G et Absoul te pat h of the file /* G et Absoulte path of the file This Java example shows how to get absolute path of a file using getAbsolutePath method of Java File class. */

    import java.io.*;public class G etAbsoulteFilePath {

    public static void main(String[] args) {String filePath = File.separator + "JavaExamples" + File.separator + "IO";

    //create new File objectFile file = new File(filePath);

    /* To get absoulte path of the file use, String getAbsolutePath() method of File class. It returns a String containing absoulte path of the file infilesystem. */

    System.out.println("Abstract file path is :" + file.getPath());System.out.println("Absolute file path is : " + file.getAbsolutePath());

    }}

    /* Output would beAbstract file path is :\JavaExamples\IOAbsolute file path is : C:\JavaExamples\IO*/

    15. G et na m e of pa rent d ire ctory/* G et name of parent directory This Java example shows how to get a name of the parent directory of a particular file or directory using getParentmethod of Java File class. */

    import java.io.*;

  • 8/6/2019 Data Input Stream

    24/34

  • 8/6/2019 Data Input Stream

    25/34

    2 5 | P a g e

    /*Output would beListing contents of C:\FileIOdemo.txtHiddenDemo.txtJavaTemp10351.javatempJavaTemp40534.javatempR eadText.txt*/

    18. M a rk file or d ire ctory Read On ly

    /* M ark file or directory R ead Only This Java example shows how set mark a particular file or directory as a read only using set R eadyOnly methodof Java File class. */

    import java.io.*;public class M arkFile R eadOnly {

    public static void main(String[] args) {

    //create file objectFile file = new File("C://FileIO//demo.txt");

    /* To mark a particular file or directory as a read only, use boolean set R eadyOnly() method of Java File class. This method returns true if theoperation was successful. */

    boolean bln M arked = file.set ReadOnly();

    System.out.println(" W as file marked read only ?: " + bln M arked);//check whether file is readonly or not using can W rite methodSystem.out.println("Is file writable ?: " + file.can W rite());

    }}

    /* Output would beW as file marked read only ?: trueIs file writable ?: false*/

    19. Rena m e file or d irectoryy R ename file or directory This Java example shows how to rename file or directory using renameTo method of Java File class. */

    import java.io.*;public class R enameFileDirectory {

    public static void main(String[] args) {//create source File objectFile oldName = new File("C://FileIO//source.txt");

    //create destination File objectFile newName = new File("C://FileIO//destination.txt");

    /* To rename a file or directory, use boolean renameTo(File destination) method of Java File class. This method returns true if the file wasrenamed successfully, false otherwise. */

    boolean isFile R enamed = oldName.renameTo(newName);

    if(isFileRenamed)System.out.println("File has been renamed");

    elseSystem.out.println("Error renaming the file");

    }}

    /*Output would beFile has been renamed*/

  • 8/6/2019 Data Input Stream

    26/34

    2 6 | P a g e

    F ileInputStream

    y R ead file in byte array using FileInputStreamy R ead file using FileInputStreamy Skip n bytes while reading the file using FileInputStream

    1. Read file in byte a rra y usi ng FileInp utSt rea m/* R ead file in byte array using FileInputStream This example shows how to read a file in byte array using Java FileInputStream

    class. This method should only be used when the file size is less than Integer. M AX_VALUE. */

    import java.io.*;public class R eadFileByteArray {

    public static void main(String[] args) {

    //create file objectFile file = new File("C://FileIO// R eadString.txt");

    try{//create FileInputStream object

    FileInputStream fin = new FileInputStream(file);

    /* Create byte array large enough to hold the content of the file. Use File.length to determine size of the file in bytes. */

    byte fileContent[] = new byte[(int)file.length()];

    /* To read content of the file in byte array, use int read(byte[] byteArray) method of java FileInputStream class. */fin.read(fileContent);

    //create string from byte arrayString strFileContent = new String(fileContent);

    System.out.println("File content : ");

    System.out.println(strFileContent);

    }catch(FileNotFoundException e){System.out.println("File not found" + e);

    }catch(IOException ioe){System.out.println("Exception while reading the file " + ioe);

    }}

    }

    /* Output would beFile content :This file is for demonstration of how to read file in byte arrayusing Java FileInputStream.*/

    2 . Read file using FileInp u tSt rea m/* R ead file using FileInputStream This example shows how to read a file using Java FileInputStream class. FileInputStream is used to read binarycontent of the file and return bytes of data */import java.io.*;public class R eadStringFromFile {

  • 8/6/2019 Data Input Stream

    27/34

    2 7 | P a g e

    public static void main(String[] args) {//create file objectFile file = new File("C://FileIO// R eadString.txt");

    int ch;StringBuffer strContent = new StringBuffer("");FileInputStream fin = null;

    try{

    /* Create new FileInputStream object. Constructor of FileInputStream throws FileNotFoundException if the agrument File does not exist. */

    fin = new FileInputStream(file);

    /* To read bytes from stream use, int read() method of FileInputStream class. This method reads a byte from stream. This method returns nextbyte of data from file or -1 if the end of the file is reached. R ead method throws IOException in case of any IO errors. */

    while( (ch = fin.read()) != -1)strContent.append((char)ch);

    /* To close the FileInputStream, use void close() method of FileInputStream class. close method also throws IOException. */fin.close();

    }

    catch(FileNotFoundException e){System.out.println("File " + file.getAbsolutePath() +

    " could not be found on filesystem");}catch(IOException ioe){System.out.println("Exception while reading the file" + ioe);

    }

    System.out.println("File contents :");System.out.println(strContent);

    /* Please note that, FileInputStream SHOULD NOT BE USED to read character data file. It is meant for reading binary data such as an image file.To read character data, File R eader should be used. */

    }}

    /*Output would beFile contents :This file is a demonstration of how to read a file using Java FileInputStream.*/

    3 . Skip n by te s whil e read ing the file using FileInp u tSt rea m/* Skip n bytes while reading the file using FileInputStream This example shows how to skip n bytes while reading the file using skip method of

    Java FileInputStream class. */

    import java.io.*;public class SkipBytes R eadFile {

    public static void main(String[] args) {

    //create file objectFile file = new File("C://FileIO// R eadString.txt");

    try{//create FileInputStream objectFileInputStream fin = new FileInputStream(file);int ch;

  • 8/6/2019 Data Input Stream

    28/34

    2 8 | P a g e

    /* To skip n bytes while reading the file, use int skip(int nBytes) method of Java FileInputStream class. This method skip over n bytes of datafrom stream. This method returns actual number of bytes that have been skipped. */

    //skip first 10 bytesfin.skip(10);

    while( (ch = fin.read()) != -1 )System.out.print((char) ch);

    }catch(FileNotFoundException e)

    {System.out.println("File not found" + e);

    }catch(IOException ioe){System.out.println("Exception while reading the file " + ioe);

    }}

    }

    F ileOutputStream

    y Append output to file using FileOutputStreamy Copy binary file using Streamsy Create FileOutputStream object from File objecty Create FileOutputStream object from String file pathy W rite byte array to a file using FileOutputStreamy W rite file using FileOutputStream

    1. Append ou tp u t t o file using FileO u tp u tSt rea m

    /*Append output to file using FileOutputStreamThis example shows how to append byte data to a file using write method of Java FileOutputStream object.

    */

    import java.io.*;

    public class AppendToFile {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//demo.txt";

    try{/** To append output to a file, use* FileOutputStream(String file, booean blnAppend) or* FileOutputStream(File file, booean blnAppend) constructor.** If blnAppend is true, output will be appended to the existing content* of the file. If false, file will be overwritten.*/

    FileOutputStream fos = new FileOutputStream(strFilePath, true);

  • 8/6/2019 Data Input Stream

    29/34

    2 9 | P a g e

    String strContent = "Append output to a file example";

    fos.write(strContent.getBytes());

    /** Close FileOutputStream using,* void close() method of Java FileOutputStream class.**/

    fos.close();

    }catch(FileNotFoundException ex){System.out.println("FileNotFoundException : " + ex);

    }catch(IOException ioe){System.out.println("IOException : " + ioe);

    }

    }}

    2 . Create FileO u tp u tSt rea m obj e ct from Fil e obj ect

    /*Create FileOutputStream object from File objectThis example shows how to skip createFileOutputStream object from File object.

    */

    import java.io.*;

    public class CreateFileOutputStreamObjectFromFile {

    public static void main(String[] args) {

    File file = new File("C://FileIO//demo.txt");

    /** To create FileOutputStream object from File object use,* FileOutputStream(File file) constructor.*/

    try{FileOutputStream fos = new FileOutputStream(file);

    }catch(FileNotFoundException ex){System.out.println("Exception : " + ex);

    }}

    }

    3 . Create FileO u tp u tSt rea m obj e ct from St ring file pat h

    /*

  • 8/6/2019 Data Input Stream

    30/34

    3 0 | P a g e

    Create FileOutputStream object from String file pathThis example shows how to create FileOutputStream object from String containingfile path.

    */

    import java.io.*;

    public class CreateFileOutputStreamObjectFromString {

    public static void main(String[] args) {

    String strFilePath = "C://FileIO//demo.txt";

    /** To create FileOutputStream object from String use,* FileOutputStream(String filePath) constructor.*/

    try{FileOutputStream fos = new FileOutputStream(strFilePath);

    }catch(FileNotFoundException ex){

    System.out.println("Exception : " + ex);}

    }}

    4. W rite file using FileO u tp u tSt rea m

    1. /* 2 . Write file using FileOutputStream 3 . This example shows how to write byte data to a file using write method of 4 . Java FileOutputStream object . 5 . */ 6 . 7 . import java . io . * ; 8 . 9 . public class WriteFile { 10. 11. public static void main ( String [] args ) { 1 2 . 1 3 . String strFilePath = "C://FileIO//demo . txt" ; 1 4 . 1 5 . try 1 6 . { 1 7 . FileOutputStream fos = new FileOutputStream ( strFilePath ); 1 8 . byt e b = 01 ; 1 9 . 2 0. /* 2 1. * To write byte data to a file, use 22 . * void write(int i) method of Java FileOutputStream class . 23 . * 24 . * This method writes given byte to a file . 25 . */ 26 . 27 . fos . write( b ); 28 . 29 . /* 3 0. * Close FileOutputStream using, 3 1. * void close() method of Java FileOutputStream class .

  • 8/6/2019 Data Input Stream

    31/34

    3 1 | P a g e

    32 . *33 . */ 34 . 35 . fos . close(); 36 . 37 . } 38 . catch ( FileNotFoundException ex ) 39 . { 4 0. System . out . println( "FileNotFoundException : " + ex ); 4 1. } 42 . catch ( IOException ioe ) 43 . { 44 . System . out . println( "IOException : " + ioe ); 45 . } 46 . 47 . } 48 . }

    InputStream

    y R ead character from console using InputStreamy R ead line of characters from console using InputStream

    1. Read cha ra cte r from co n sole using Inp u tSt rea m

    1. /* 2 . Read character from console using InputStream 3 . This example shows how to read a character from console window . 4 . This example also shows how to read user entered data from console window 5 . using System . in 6 . */ 7 . 8 . import java . io . IOException ; 9 . 10. public class ReadCharFromConsoleExample { 11. 1 2 . public static void main ( String [] args ) { 1 3 . 1 4 . /* 1 5 . * To read a character from console use, 1 6 . * read method of InputStream class variable System . in 1 7 . * which defined as static variable . 1 8 . */ 1 9 . 2 0. i n t iChar = 0 ; 2 1. 22 . System . out . println( "Read user input character example" ); 23 . try 24 . { 25 . System . out . println( "Enter a character to continue" ); 26 . iChar = System . in . read(); 27 . System . out . println( "Char entered was : " + ( char ) iChar ); 28 . } 29 . catch ( IOException e ) 3 0. { 3 1. System . out . println( "Error while reading : " + e ); 32 . } 33 . } 34 . } 35 . 36 . /*

  • 8/6/2019 Data Input Stream

    32/34

    32 | P a g e

    37 . Typical output would be 38 . Read user input character example 39 . Enter a character to continue 4 0. a 4 1. Char entered was : a 42 . */

    2 . Read line of ch a ra cte rs from co n sol e usi ng Inp u tSt rea m

    1. /* 2 . Read line of characters from console using InputStream 3 . This example shows how to read a line or string from console window 4 . using readLine method of BufferedInputStream . 5 . */ 6 . 7 . import java . io . BufferedReader ; 8 . import java . io . IOException ; 9 . import java . io . InputStreamReader ; 10. 11. public class ReadLineFromConsoleExample { 1 2 . 1 3 . public static void main ( String [] args ) { 1 4 . 1 5 . /* 1 6 . * To read line or string from console use, 1 7 . * readLine method of BufferedReader class . 1 8 . */ 1 9 . 2 0. 2 1. BufferedReader br = 22 . new BufferedReader ( new InputStreamReader ( System . in)); 23 . 24 . String strLine = n ull ; 25 . 26 . System . out . println( "Reading line of characters from console" ); 27 . System . out . println( "Enter exit to quit" ); 28 . 29 . try 3 0. { 3 1. 32 . w hil e ( ( strLine = br . readLine()) != n ull ) 33 . { 34 . if ( strLine . equals( "exit" )) 35 . br e ak ; 36 . 37 . System . out . println( "Line entered : " + strLine ); 38 . 39 . } 4 0. 4 1. br . close(); 42 . 43 . } 44 . catch ( Exception e ) 45 . { 46 . System . out . println( "Error while reading line from console : " + e ); 47 . } 48 . } 49 . }

  • 8/6/2019 Data Input Stream

    33/34

    33 | P a g e

    J ava String ExamplesThe String class implements immutable character strings, which are read-only once the string object has been created and initialized. All stringliterals in Java programs, are implemented as instances of String class.

    The easiest way to create a Java String object is using a string literal:

    1. String str 1 = "I can't be changed once created!" ;

    A Java string literal is a reference to a String object. Since a String literal is a reference, it can be manipulated like any other String reference. i.e. itcan be used to invoke methods of String class.

    For example,

    1. i n t myLenght = "Hello world" . length();

    The Java language provides special support for the string concatenation operator (+), which has been overloaded for Java Strings objects. Stringconcatenation is implemented through the StringBuffer class and its append method.

    For example,

    1. String finalString = "Hello" + "World" ;

    W ould be executed as

    1. String finalString = new StringBuffer () . append( "Hello" ) . append( "World" ) . toString();

    The Java compiler optimizes handling of string literals. Only one String object is shared by all strings having same character sequence. Such stringsare said to be interned, meaning that they share a unique String object. The Java String class maintains a private pool where such strings areinterned.

    For example,

    1. String str 1 ="Hello" ; 2 . String str2 ="Hello" ; 3 . I f ( str 1 == str2 ) 4 . System . out . println( "Equal" );

    W ould print Equal when executed.

    Since the Java String objects are immutable, any operation performed on one String reference will never have any effect on other references

    denoting the same object.

    String ConstructorsString class provides various types of constructors to create String objects. Some of them are,

    String()Creates a new String object whose content is empty i.e. "".

    String(String s)Creates a new String object whose content is same as the String object passed as an argument.

  • 8/6/2019 Data Input Stream

    34/34

    Note: Invoking String constructor creates a new string object, means it does not intern the String. Interned String object reference can be obtainedby using intern() method of the String class.

    String also provides constructors that take byte and char array as an argument and returns String object.

    String equality - Compare Java StringString class overrides the equals() method of the Object class. It compares the content of the two string object and returns the boolean valueaccordingly.

    For example,

    1. String str 1 ="Hello" ; 2 . String str2 ="Hello" ; 3 . String str3 = new String ( "Hello" ) //Using constructor . 4 . 5 . I f ( str 1 == str2 ) 6 . System . out . println( "Equal 1 " ); 7 . E ls e 8 . System . out . println( "Not Equal 1 " ); 9 . 10. I f ( str 1 == str3 ) 11. System . out . println( "Equal 2" ); 1 2 . E ls e 1 3 . System . out . println( "I am constructed using constructor, hence not interned" ); 1 4 . 1 5 . I f ( str 1. equals( str3 ) ) 1 6 . System . out . println( "Equal 3" ); 1 7 . E ls e 1 8 . System . out . println( "Not Equal 3" );

    The output would be,Equal 1Not Equal 2Equal 3

    Note that == compares the references not the actual contents of the String object; W here as equals method compares actual contents of two Stringobjects.

    String class also provides another method equalsIgnoreCase() which ignores the case of contents while comparing.

    Apart from these methods String class also provides compareTo methods.

    int compareTo(String str2)This method compares two Strings and returns an int value. It returns- value 0, if this string is equal to the string argument- a value less than 0, if this string is less than the string argument- a value greater than 0, if this string is greater than the string argument

    int compareTo(Object object)This method behaves exactly like the first method if the argument object is actually a String object; otherwise, it throws a ClassCastException.