0% found this document useful (0 votes)
316 views

Datainputstream: 1. Read Boolean From File Using Datainputstream

The document discusses using the DataInputStream class in Java to read different data types from files, including boolean, byte array, byte, char, double, float, int, long, and short. For each data type there is a code example showing how to create a DataInputStream from a FileInputStream, use the appropriate read method like readBoolean() or readInt() to read the data type from the file, and close the DataInputStream.

Uploaded by

Taqi Hassan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
316 views

Datainputstream: 1. Read Boolean From File Using Datainputstream

The document discusses using the DataInputStream class in Java to read different data types from files, including boolean, byte array, byte, char, double, float, int, long, and short. For each data type there is a code example showing how to create a DataInputStream from a FileInputStream, use the appropriate read method like readBoolean() or readInt() to read the data type from the file, and close the DataInputStream.

Uploaded by

Taqi Hassan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

DatainputStream

 Read boolean from file using DataInputStream


 Read byte array from file using DataInputStream
 Read byte from file using DataInputStream
 Read char from file using DataInputStream
 Read double from file using DataInputStream
 Read float from file using DataInputStream
 Read int from file using DataInputStream
 Read long from file using DataInputStream
 Read short from file using DataInputStream
 Read unsigned byte from file using DataInputStream

1. Read boolean from file using DataInputStream

/* Read 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 ReadBooleanFromFile {

public static void main(String[] args) {

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

try
{
//create FileInputStream object
FileInputStream 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)
{
1|Page
System.out.println("IOException : " + ioe);
}
}
}

2. Read byte array from file using DataInputStream

/* Read byte array from file using DataInputStream This Java example shows how to read an array of bytes from file using
read 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 ReadByteArrayFromFile {

public static void main(String[] args) {

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

try
{
//create FileInputStream object
FileInputStream 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 byte from file using DataInputStream

/* Read 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 ReadByteFromFile {

2|Page
public static void main(String[] args) {

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

try
{
//create FileInputStream object
FileInputStream 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 char from file using DataInputStream

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

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


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

public class ReadCharFromFile {

public static void main(String[] args) {

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

try
{
//create FileInputStream object
FileInputStream 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). */

3|Page
char ch = din.readChar();

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

/* * 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);
}
}
}

5. Read double from file using DataInputStream

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

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


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

public class ReadDoubleFromFile {

public static void main(String[] args) {

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

Try {
//create FileInputStream object
FileInputStream 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)
{

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

6. Read float from file using DataInputStream

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

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


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

public class ReadFloatFromFile {

public static void main(String[] args) {

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

try
{
//create FileInputStream object
FileInputStream 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 file using DataInputStream

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

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


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

public class ReadIntFromFile {

5|Page
public static void main(String[] args) {

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

try
{
//create FileInputStream object
FileInputStream 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();

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 file using DataInputStream

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

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


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

public class ReadLongFromFile {

public static void main(String[] args) {

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

try
{
//create FileInputStream object
FileInputStream 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 and
returns it as a long value. */

6|Page
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);
}
}
}

9. Read short from file using DataInputStream


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

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


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

public class ReadShortFromFile {

public static void main(String[] args) {

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

try
{
//create FileInputStream object
FileInputStream 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)

7|Page
{
System.out.println("IOException : " + ioe);
}
}
}

10. Read unsigned byte from file using DataInputStream


/* Read 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 ReadUnsignedByteFromFile {

public static void main(String[] args) {

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

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

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

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
 Create DataOutputStream from FileOutputStream
 Determine number of bytes written to DataOutputStream
 Flush output stream
 Write boolean to a file using DataOutputStream
 Write byte to a file using DataOutputStream
 Write char to a file using DataOutputStream

8|Page
 Write double to a file using DataOutputStream
 Write float to a file using DataOutputStream
 Write int to a file using DataOutputStream
 Write long to a file using DataOutputStream
 Write short to a file using DataOutputStream
 Write String as bytes to a file using DataOutputStream
 Write String as characters to a file using DataOutputStream

1. Create DataOutputStream from FileOutputStream

/* 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 object
FileOutputStream fos = new FileOutputStream(strFilePath);

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

DataOutputStream dos = new DataOutputStream(fos);


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

2. Determine number of bytes written to DataOutputStream

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

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

public class NumberOfBytesWritten {

public static void main(String[] args) {

String strFilePath = "C://FileIO//NumberOfBytes.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);

String str = "Example to show number of bytes written to stream";

9|Page
dos.writeBytes(str);

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

int bytesWritten = dos.size();


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

dos.close();

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

3. Flush output stream


/* 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//WriteByte.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);

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 stream


dos.close();

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

4. Write boolean to a file using DataOutputStream


/* Write 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. */

10 | P a g e
import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

public class WriteBooleanToFile {

public static void main(String[] args) {

String strFilePath = "C://FileIO//WriteBoolean.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);

boolean b = false;

/* * To write a boolean value to a file, use * void writeBoolean(boolean b) method of Java DataOutputStream class. * This method writes
specified 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);
}
}
}

5. Write byte to a file using DataOutputStream


/* Write byte to a file using DataOutputStream This Java example shows how to write a Java byte primitive value to a file using writeByte
method of Java DataOutputStream class. */

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

public class WriteByteToFile {

public static void main(String[] args) {

String strFilePath = "C://FileIO//WriteByte.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);

int i = 1;

11 | P a g e
/* * 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. Write char to a file using DataOutputStream


/* Write char to a file using DataOutputStream This Java example shows how to write a Java character primitive value to a
file using writeChar method of Java DataOutputStream class. */

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

public class WriteCharToFile {

public static void main(String[] args) {

String strFilePath = "C://FileIO//WriteChar.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);

int ch = 65;

/* * To write a char value to a file, use * void writeChar(int ch) method of Java DataOutputStream class. * This method writes specified char
to 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. Write double to a file using DataOutputStream


/* Write 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. */

12 | P a g e
import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;

public class WriteDoubleToFile {

public static void main(String[] args) {

String strFilePath = "C://FileIO//WriteDouble.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);

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. Write float to a file using DataOutputStream

 Write float to a file using DataOutputStream This Java example shows how to write a Java float primitive value to a file using
writeFloat method of Java DataOutputStream class. */

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

public class WriteFloatToFile {

public static void main(String[] args) {

String strFilePath = "C://FileIO//WriteFloat.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);

13 | P a g e
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 to
output 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 to
underlying output stream. */

dos.writeFloat(f);

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

dos.close();

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

}
}

9. Write int to a file using DataOutputStream


/* Write 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 WriteIntToFile {

public static void main(String[] args) {

String strFilePath = "C://FileIO//WriteInt.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);

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 to
output stream as 4 bytes value. */

dos.writeInt(i);

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

dos.close();

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

14 | P a g e
}
}

10. Write long to a file using DataOutputStream


/* Write 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 WriteLongToFile {

public static void main(String[] args) {

String strFilePath = "C://FileIO//WriteLong.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);

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. Write short to a file using DataOutputStream


/* Write 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 WriteShortToFile {

public static void main(String[] args) {

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

try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
15 | P a g e
/* * 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. Write String as bytes to a file using DataOutputStream


/* Write 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 WriteStringAsBytesToFile {

public static void main(String[] args) {

String strFilePath = "C://FileIO//WriteStringAsBytes.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);

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)
{
System.out.println("IOException : " + e);

16 | P a g e
} } }

13. Write String as characters to a file using DataOutputStream

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

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

public class WriteStringAsCharsToFile {

public static void main(String[] args) {

String strFilePath = "C://FileIO//WriteStringAsChars.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);

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);
}
}}

File And Directory


 Compare two file paths

17 | P a g e
 Construct file path
 Create directory
 Create directory along with required nonexistent parent directories
 Create new empty file
 Create temporary file
 Create temporary file in specified directory
 Delete file or directory
 Delete file or directory when virtual machine terminates
 Determine File or Directory
 Determine if a file can be read
 Determine if a file can be written
 Determine if file or directory exists
 Determine if File or Directory is hidden
 Get Absoulte path of the file
 Get File size in bytes
 Get Last modification time of a file or directory
 Get name of parent directory
 Get name of specified file or directory
 Get parent directory as a File object
 List contents of a directory
 List Filesystem roots
 Mark file or directory Read Only
 Rename file or directory
 Set last modified time of a file or directory

1. Compare two file paths


/* 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 object
File file1 = new File("C://FileIO//demo1.txt");

//create second file object


File 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. Construct file path


/* 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. * Windows based machines has path like \dir1\dir2 while UNIX
based machines * has path like /dir1/dir2 */

18 | P a g e
String filePath = File.separator + "JavaExamples" + File.separator + "IO";

//create new File object


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 Windows machine would be,
File path is : \JavaExamples\IO

Output in UNIX machine would be,


File path is : /JavaExamples/IO
*/

3. Create directory
/* 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 object
File 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 was
created successfully, false * otherwise. */

boolean isDirectoryCreated = dir.mkdir();

if(isDirectoryCreated)
System.out.println("Directory created successfully");
else
System.out.println("Directory was not created successfully");
}
}

/*
Output would be
Directory created successfully
*/

4. Create directory along with required nonexistent parent directories


/* Create directory along with required nonexistent parent directories This Java example shows how to create a directory along with the required
parent 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 object


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

19 | P a g e
/* * To create directory along with the required nonexistent parent directories use, * boolean mkdirs() method of Java File class. * This method
returns 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)
System.out.println("Directory created along with required nonexistent
parent directories");
else
System.out.println("Failed to create directory");
}
}

/*
Output would be
Directory created along with required nonexistent parent directories
*/

5. Create new empty 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 object
File 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 new
empty 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("Was 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 was
already * exist. */
}
}

/*
Output would be
Was file C:\demo.txt created ? : true
*/

6. Create temporary 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.*;

20 | P a g e
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 generate
suffix 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
{
//create temporary file wihtout extension suffix
file1 = File.createTempFile("JavaTemp", null);

//create temporary file with specified extension suffix


file2 = 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 be


Temporary file without suffix extension: C:\Temp\JavaTemp45096.tmp
Temporary file with suffix extension: C:\Temp\JavaTemp45097.javatemp
*/

7. Create temporary file in specified directory


/* 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 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 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 which
the 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. */

21 | P a g e
System.out.println("Temporary file created at : " + file.getPath());
}
}

/* Typical output would be


Temporary file created at : C:\FileIO\JavaTemp40534.javatemp
*/

8. Delete file or directory


/* Delete file or directory This Java example shows how to delete a particular file or directory from filesystem using delete method of Java File
class. */

import java.io.*;
public class DeleteFileOrDirectory {
public static void main(String[] args) {
//create file object
File 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 successfully
deleted. If the file is a directory, it must be empty. */

boolean blnDeleted = file.delete();


System.out.println("Was file deleted ? : " + blnDeleted);

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

/* Output would be
Was file deleted ? : true
*/

9. Delete file or directory when virtual machine terminates


/* Delete file or directory when virtual machine terminates This Java example shows how to delete a particular file or directory from filesystem
when Java Virtual Machine terminates using deleteOnExit method of Java File class */

import java.io.*;
public class DeleteFileWhenVMTerminates {
public static void main(String[] args) {
//create File object
File file = new File("C://FileIO//DeleteDemo.txt");

/* To delete a particular file or directory when Java VM exits, use void deleteOnExit() method. This method request to delete a specified file or
directory 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. Determine File or Directory


/* 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 filesystem
using isFile and isDirectory methods of Java File class. */

import java.io.*;
public class DetermineDirOrFile {
public static void main(String[] args) {
//create file object
File file = new File("C://FileIO");

22 | P a g e
/* 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 and
its a normal file. */

boolean isFile = file.isFile();


if(isFile)
System.out.println(file.getPath() + " is a file.");
else
System.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 the
directory EXISTS and its a directory. */

boolean isDirectory = file.isDirectory();


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

}
}

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

11. Determine if a file can be read


 Determine if a file can be read This Java example shows how to determine if a particular file has a read permission using canRead
method of Java File class. */

import java.io.*;
public class DetermineReadFile {
public static void main(String[] args) {

//create file path


String filePath = "C:/FileIO/ReadText.txt";

//create File object


File file = new File(filePath);

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

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

/* Output would be
File C:\FileIO\ReadText.txt can be read
*/

12. Determine if a file can be written

23 | P a g e
/* Determine if a file can be written This Java example shows how to determine if a particular file has a write permission using canWrite method
of Java File class. */

import java.io.*;
public class DetermineWriteFile {
public static void main(String[] args) {
//create file path
String filePath = "C:/FileIO/ReadText.txt";

//create File object


File file = new File(filePath);

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

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

/* Output would be
File C:\FileIO\ReadText.txt can be written
*/

13. Determine if file or directory exists

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

import java.io.*;
public class DetermineIfFileExists {
public static void main(String[] args) {

//create file object


File 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 particular
file 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 be
Does file C:\FileIO\ExistsDemo.txt exist ?: true
*/

14. Get Absoulte path of the file


/* Get 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 GetAbsoulteFilePath {
public static void main(String[] args) {
String filePath = File.separator + "JavaExamples" + File.separator + "IO";

24 | P a g e
//create new File object
File 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 in
filesystem. */

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


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

}
}

/* Output would be
Abstract file path is :\JavaExamples\IO
Absolute file path is : C:\JavaExamples\IO
*/

15. Get name of parent directory


/* Get name of parent directory This Java example shows how to get a name of the parent directory of a particular file or directory using getParent
method of Java File class. */

import java.io.*;
public class GetParentDirectory {
public static void main(String[] args) {

//create file object


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

/* To get parent directory of a particular file, use String getParent() method of Java File class. */

String strParentDirectory = file.getParent();


System.out.println("Parent directory is : " + strParentDirectory);
}
}

/*Output would be
Parent directory is : C:\FileIO
*/

16. Get name of specified file or directory


 Get name of specified file or directory This Java example shows how to get a name of specified file or directory denoted by a path using
getName method of Java File class. */

import java.io.*;
public class GetNameOfFileOrDirectory {
public static void main(String[] args) {

//create file object


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

/* To get a name of file or directory denoted by a path, use String getName() method of Java File class. This method returns name of the file or
directory denoted by path. */

String strFileName = file.getName();


System.out.println("File name is : " + strFileName);
}
}

25 | P a g e
/* Output would be
File name is : FileDemo.txt
*/

17. List contents of a directory


/* List contents of a directory This Java example shows how list contents(files and sub-directories) of a directory using list method of Java File class.
*/

import java.io.*;
public class ListContentOfDirectory {
public static void main(String[] args) {

//create file object


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

/* To list contents of a directory use, String[] list() method of Java File class. This method returns an array of Strings containing name of files and
sub-directories. It reuturns an empty array, if directory is empty, and null if file does not denotes a directory. */

String[] files = file.list();

System.out.println("Listing contents of " + file.getPath());


for(int i=0 ; i < files.length ; i++)
{
System.out.println(files[i]);
}
}
}

/*Output would be
Listing contents of C:\FileIO
demo.txt
HiddenDemo.txt
JavaTemp10351.javatemp
JavaTemp40534.javatemp
ReadText.txt
*/

18. Mark file or directory Read Only


/* Mark file or directory Read Only This Java example shows how set mark a particular file or directory as a read only using setReadyOnly method of
Java File class. */

import java.io.*;
public class MarkFileReadOnly {
public static void main(String[] args) {

//create file object


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

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

boolean blnMarked = file.setReadOnly();


System.out.println("Was file marked read only ?: " + blnMarked);
//check whether file is readonly or not using canWrite method
System.out.println("Is file writable ?: " + file.canWrite());
}
}

/* Output would be
Was file marked read only ?: true
Is file writable ?: false

26 | P a g e
*/

19. Rename file or directory


 Rename 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 RenameFileDirectory {
public static void main(String[] args) {
//create source File object
File oldName = new File("C://FileIO//source.txt");

//create destination File object


File 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 was
renamed successfully, false otherwise. */

boolean isFileRenamed = oldName.renameTo(newName);

if(isFileRenamed)
System.out.println("File has been renamed");
else
System.out.println("Error renaming the file");
}
}

/*Output would be
File has been renamed
*/

FileInputStream
 Read file in byte array using FileInputStream
 Read file using FileInputStream
 Skip n bytes while reading the file using FileInputStream

1. Read file in byte array using FileInputStream


/* Read 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.MAX_VALUE. */

import java.io.*;
public class ReadFileByteArray {
public static void main(String[] args) {

//create file object


File file = new File("C://FileIO//ReadString.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()];

27 | P a g e
/* 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 array


String 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 be
File content :
This file is for demonstration of how to read file in byte array
using Java FileInputStream.
*/

2. Read file using FileInputStream


/* Read file using FileInputStream This example shows how to read a file using Java FileInputStream class. FileInputStream is used to read binary
content of the file and return bytes of data */
import java.io.*;
public class ReadStringFromFile {
public static void main(String[] args) {
//create file object
File file = new File("C://FileIO//ReadString.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 next
byte of data from file or -1 if the end of the file is reached. Read 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() +
28 | P a g e
" 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, FileReader should be used. */
}
}

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

3. Skip n bytes while reading the file using FileInputStream


/* 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 SkipBytesReadFile {
public static void main(String[] args) {

//create file object


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

try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(file);
int ch;
/* 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 data
from stream. This method returns actual number of bytes that have been skipped. */

//skip first 10 bytes


fin.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);
}
}
}

29 | P a g e
FileOutputStream
 Append output to file using FileOutputStream
 Copy binary file using Streams
 Create FileOutputStream object from File object
 Create FileOutputStream object from String file path
 Write byte array to a file using FileOutputStream
 Write file using FileOutputStream

1. Append output to file using FileOutputStream

/*
Append output to file using FileOutputStream
This 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);


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);
}

30 | P a g e
}
}

2. Create FileOutputStream object from File object

/*
Create FileOutputStream object from File object
This 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 FileOutputStream object from String file path

/*
Create FileOutputStream object from String file path
This example shows how to create FileOutputStream object from String containing
file 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

31 | P a g e
{
FileOutputStream fos = new FileOutputStream(strFilePath);
}
catch(FileNotFoundException ex)
{
System.out.println("Exception : " + ex);
}
}
}

4. Write file using FileOutputStream

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) {
12.  
13. String strFilePath = "C://FileIO//demo.txt";
14.  
15. try
16. {
17. FileOutputStream fos = new FileOutputStream(strFilePath);
18. byte b = 01;
19.  
20. /*
21.   * 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. /*
30.   * Close FileOutputStream using,
31.   * void close() method of Java FileOutputStream class.
32.   *
33.   */
34.  
35. fos.close();
36.  
37. }
38. catch(FileNotFoundException ex)
39. {
40. System.out.println("FileNotFoundException : " + ex);
41. }
42. catch(IOException ioe)
43. {
44. System.out.println("IOException : " + ioe);
45. }
46.  
47. }
48. }

32 | P a g e
InputStream
 Read character from console using InputStream
 Read line of characters from console using InputStream

1. Read character from console using InputStream

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.  
12. public static void main(String[] args) {
13.  
14. /*
15. * To read a character from console use,
16. * read method of InputStream class variable System.in
17. * which defined as static variable.
18. */
19.  
20. int iChar = 0;
21.  
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)
30. {
31. System.out.println("Error while reading : " + e);
32. }
33. }
34. }
35.  
36. /*
37. Typical output would be
38. Read user input character example
39. Enter a character to continue
40. a
41. Char entered was : a
42. */

2. Read line of characters from console using InputStream

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;

33 | P a g e
9. import java.io.InputStreamReader;
10.  
11. public class ReadLineFromConsoleExample {
12.  
13. public static void main(String[] args) {
14.  
15. /*
16. * To read line or string from console use,
17. * readLine method of BufferedReader class.
18. */
19.  
20.  
21. BufferedReader br =
22. new BufferedReader(new InputStreamReader(System.in));
23.  
24. String strLine = null;
25.  
26. System.out.println("Reading line of characters from console");
27. System.out.println("Enter exit to quit");
28.  
29. try
30. {
31.  
32. while( (strLine = br.readLine()) != null)
33. {
34. if(strLine.equals("exit"))
35. break;
36.  
37. System.out.println("Line entered : " + strLine);
38.  
39. }
40.  
41. br.close();
42.  
43. }
44. catch(Exception e)
45. {
46. System.out.println("Error while reading line from console : " + e);
47. }
48. }
49. }

Java String Examples


The String class implements immutable character strings, which are read-only once the string object has been created and initialized. All string
literals 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 str1 = "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. it
can be used to invoke methods of String class.

For example,

1. int myLenght = "Hello world".length();

34 | P a g e
The Java language provides special support for the string concatenation operator (+), which has been overloaded for Java Strings objects. String
concatenation is implemented through the StringBuffer class and its append method.

For example,

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

Would 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 strings
are said to be interned, meaning that they share a unique String object. The Java String class maintains a private pool where such strings are
interned.

For example,

1. String str1="Hello";
2. String str2="Hello";
3. If(str1 == str2)
4. System.out.println("Equal");

Would 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 Constructors
String 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.

Note: Invoking String constructor creates a new string object, means it does not intern the String. Interned String object reference can be obtained
by 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 String


String class overrides the equals() method of the Object class. It compares the content of the two string object and returns the boolean value
accordingly.

For example,

1. String str1="Hello";
2. String str2="Hello";
3. String str3=new String("Hello") //Using constructor.
4.  
5. If(str1 == str2)
6. System.out.println("Equal 1");
7. Else
8. System.out.println("Not Equal 1");

35 | P a g e
9.  
10. If(str1 == str3)
11. System.out.println("Equal 2");
12. Else
13. System.out.println("I am constructed using constructor, hence not interned");
14.  
15. If( str1.equals(str3) )
16. System.out.println("Equal 3");
17. Else
18. System.out.println("Not Equal 3");

The output would be,


Equal 1
Not Equal 2
Equal 3

Note that == compares the references not the actual contents of the String object; Where as equals method compares actual contents of two String
objects.

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.

36 | P a g e

You might also like