Datainputstream: 1. Read Boolean From File Using Datainputstream
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. */
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(strFilePath);
/* * 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();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
1|Page
System.out.println("IOException : " + ioe);
}
}
}
/* 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. */
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(strFilePath);
/* * 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. */
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
}
}
/* 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. */
2|Page
public static void main(String[] args) {
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(strFilePath);
/* * To read a Java byte primitive from file, use * byte readByte() method of Java DataInputStream class. */
byte b = din.readByte();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
}
}
/* 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. */
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(strFilePath);
/* * 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();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
}
}
/*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. */
Try {
//create FileInputStream object
FileInputStream fin = new FileInputStream(strFilePath);
/* * 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();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
4|Page
System.out.println("IOException : " + ioe);
}
}
}
/* 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. */
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(strFilePath);
/* * 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();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
}
}
*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.*/
5|Page
public static void main(String[] args) {
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(strFilePath);
/* * 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();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
}
}
/* 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. */
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(strFilePath);
/* * 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();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
}
}
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(strFilePath);
/* * 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();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
7|Page
{
System.out.println("IOException : " + ioe);
}
}
}
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(strFilePath);
/* * 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();
}
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
/* Create DataOutputStream from FileOutputStream This Java example shows how to create DataOutputStream from FileOutputStream object.
*/
try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
/* 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. */
try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
9|Page
dos.writeBytes(str);
/* * To determine total number of bytes written to underlying stream, use * int size() method.*/
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
}
}
try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
/* * 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();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
}
}
10 | P a g e
import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;
try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
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);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
}
}
try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
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);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
}
}
try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
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);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
}
}
12 | P a g e
import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException;
try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
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);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
}
}
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. */
try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
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);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
}
}
try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
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);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
14 | P a g e
}
}
try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
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);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
}
}
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. */
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);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
}
}
try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
/* * 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);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
16 | P a g e
} } }
/* 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. */
try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
/* * 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);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
}}
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
import java.io.*;
public class CompareTwoFilePaths {
/* * 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!");
}
}
}
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";
/* * Please note that creating file object DOES NOT actually create a file. * It DOES NOT have any effects on the filesystem. */
}
}
/*
Output in Windows 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. */
if(isDirectoryCreated)
System.out.println("Directory created successfully");
else
System.out.println("Directory was not created successfully");
}
}
/*
Output would be
Directory created successfully
*/
import java.io.*;
public class CreateDirParentDir {
public static void main(String[] args) {
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. */
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
*/
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. */
/* * 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
*/
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. */
try
{
//create temporary file wihtout extension suffix
file1 = File.createTempFile("JavaTemp", null);
}
catch(IOException ioe)
{
System.out.println("Exception creating temporary file : " + ioe);
}
}
}
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. */
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());
}
}
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. */
/* 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
*/
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. */
}
}
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. */
/* 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. */
}
}
/* Output would be
C:\FileIO is not a file.
C:\FileIO is a directory.
*/
import java.io.*;
public class DetermineReadFile {
public static void main(String[] args) {
/* 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
*/
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";
/* 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
*/
/* 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) {
/* 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. */
/*Output would be
Does file C:\FileIO\ExistsDemo.txt exist ?: true
*/
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. */
}
}
/* Output would be
Abstract file path is :\JavaExamples\IO
Absolute file path is : C:\JavaExamples\IO
*/
import java.io.*;
public class GetParentDirectory {
public static void main(String[] args) {
/* To get parent directory of a particular file, use String getParent() method of Java File class. */
/*Output would be
Parent directory is : C:\FileIO
*/
import java.io.*;
public class GetNameOfFileOrDirectory {
public static void main(String[] args) {
/* 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. */
25 | P a g e
/* Output would be
File name is : FileDemo.txt
*/
import java.io.*;
public class ListContentOfDirectory {
public static void main(String[] args) {
/* 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. */
/*Output would be
Listing contents of C:\FileIO
demo.txt
HiddenDemo.txt
JavaTemp10351.javatemp
JavaTemp40534.javatemp
ReadText.txt
*/
import java.io.*;
public class MarkFileReadOnly {
public static void main(String[] args) {
/* 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. */
/* Output would be
Was file marked read only ?: true
Is file writable ?: false
26 | P a g e
*/
import java.io.*;
public class RenameFileDirectory {
public static void main(String[] args) {
//create source File object
File oldName = new File("C://FileIO//source.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. */
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
import java.io.*;
public class ReadFileByteArray {
public static void main(String[] args) {
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. */
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);
}
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.
*/
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. */
/* 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. */
/* 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);
}
/* 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.
*/
import java.io.*;
public class SkipBytesReadFile {
public static void main(String[] args) {
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. */
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
/*
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.*;
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.
*/
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
}
}
/*
Create FileOutputStream object from File object
This example shows how to skip createFileOutputStream object from File object.
*/
import java.io.*;
/*
* 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);
}
}
}
/*
Create FileOutputStream object from String file path
This example shows how to create FileOutputStream object from String containing
file path.
*/
import java.io.*;
/*
* 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);
}
}
}
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. /*
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. */
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. }
The easiest way to create a Java String object is using a string literal:
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,
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,
Would be executed as
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");
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.
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");
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.
36 | P a g e