0% found this document useful (0 votes)
62 views75 pages

Pug Files

The document discusses input/output (I/O) in Java. It describes that I/O uses streams to process input and produce output. There are two categories of stream classes in Java - byte stream classes and character stream classes. Byte stream classes are used for binary data input/output using methods like read() and write(), while character stream classes are more efficient for text. The document also provides examples of reading from and writing to files using FileInputStream and FileOutputStream classes.

Uploaded by

excitekarthik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views75 pages

Pug Files

The document discusses input/output (I/O) in Java. It describes that I/O uses streams to process input and produce output. There are two categories of stream classes in Java - byte stream classes and character stream classes. Byte stream classes are used for binary data input/output using methods like read() and write(), while character stream classes are more efficient for text. The document also provides examples of reading from and writing to files using FileInputStream and FileOutputStream classes.

Uploaded by

excitekarthik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 75

JAVA FILES

IO

I/O is used to process the input & produce the output based
on the input
The input & output operations are performed by using
the concept of streams.
java.io package contains all the classes required for input
and output operations.
READING & WRITING IN JAVA

Java provides many classes to perform the program input and
output

Program I/O refers to any I/O performed by the program

File I/O refers specifically to I/O performed on files.

STREAM
 A stream is a sequence of data.

 In java it is a composed of bytes.

THREE STREAMS
1. System.out : Standard output stream
2. System.in : Standard input stream
3. System.err : Standard error
STREAM CLASSES
The streams in java are divided into two categories
I. Byte Stream Classes
II. Character Stream Classes
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
BYTE STREAM CLASSES

Byte stream gives a convenient way for handling input and output of
bytes.

Byte Streams are used for handling bytes

Binary data (bytes) are stored either as 8-bit byte or an ASCII
character code set

These classes are used to read and write binary data.
Top two classes
1. Input Stream : used for reading
2. OutputStream : used for writing
Important methods
1. read() : reading data one byte at a time
2. write() : writing data one byte at a time
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
InputStream methods
S.N Method Purpose

1. read(int byte) Reads a byte from the input stream

2. read(byte b[]) Reads an array of bytes into b

3. read(byte b[], int m, int n) Reads m bytes into b starting from nth byte

4. reset() Go back to the beginning of the stream

5. available() Gives no. of bytes available in the input

6. close() Closes the input stream.

OutputStream methods

S.N Method Purpose

1. write(int byte) Writes a byte to the output stream


Return type : int

2. write(byte b[]) writes all bytes in the array b to the output


Return type : byte array

3. Write(byte b[], int m, int n) writes m bytes from array b starting from
nth byte
Return type : byte array

4. close() Closes the output stream.


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
CHARACTER STREAM CLASSES

 Character stream gives a convenient way for handling input and


output of characters.

 In some cases, character streams are more efficient than


byte streams.

CS9256 Web Technology IT-4/8-S Page 5 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
FILE OUTPUT STREAM

It is an output stream for writing data to file.


Handling bytes of data
It is a complete class. So creating an object is possible.

Syntax
FileOutputStream fin=new FileOutputStream (“out.txt”);
Drawbacks
It is not possible to write the primitive data types (e.g: int, float, char) to
file.

I. EXAMPLE OF FILE OUTPUT STREAM CLASS


1. SOURCE CODE
/ subpackage named “files.FileOuputStream”
package files.FileOutputStream;
import java.io.*;
public class Fos1 {
FileOutputStream fout;
FileInputStream fin;
String text="Sachin is a best ODI player in the world...";

void fcreat()throws Exception handle runtime errors, if any
{
try
{
fout=new FileOutputStream("cric.txt");
/ encode the string into a sequence of bytes & stores into a byte array
byte[] words=text.getBytes();
CS9256 Web Technology IT-4/8-S Page 6 of 63
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
// write byte array to file
fout.write(words);
fout.close();
System.out.println("File was created successfully...");
}
catch(FileNotFoundException e)
{
System.out.println("File not found...");
}
}
void fdisp()throws Exception
{
int ch;
try
{
fin=new FileInputStream("cric.txt");
System.out.println("Contents of the file");
System.out.println("-------------------------------------------------------------");
// read the contens of a file using read() method
while((ch=fin.read())!=-1){
System.out.print((char)ch);
}
System.out.println();
OR
/*
// find the length of a file using available()
int len=fin.available();
// display the file contents using fin.read()
for(int i=0;i<len;i++)
{
System.out.print((char)fin.read());
}
System.out.println();
CS9256 Web Technology IT-4/8-S Page 7 of 63
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
*/
// close the file
fin.close();
}
catch(FileNotFoundException e)
{
System.out.println("File not found...");
}
}
public static void main(String[] args)throws Exception
{
System.out.println("===================================");
System.out.println("File Creation & Retrieval using ByteStream class");
System.out.println("===================================");
/ object creation using new modifier
Fos1 obj=new Fos1();
/ call all the instance methods using
object obj.fcreat();
obj.fdisp();
System.out.println("-------------------------------------------------------------");
}
}

CS9256 Web Technology IT-4/8-S Page 8 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
2. OUTPUT

Explanation

Java Application
110011011101

fout

cric.txt
CS9256 Web Technology IT-4/8-S Page 9 of 63
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
FILE INPUT STREAM

It is an input stream for reading data from file.


Gets input bytes from a file. (byte oriented data)
Input file can be: java file, image file, video files etc.
Drawbacks
It is not possible to read the primitives data (basic data types) from a
file.
II.FILE RETRIEVAL USING SIMPLE READ() METHOD
1. SOURCE CODE
package files_bytes;
import java.io.*;
public class FileRead{
FileInputStream fi
fin;
int ch;
void disp()throws Exception
{
try
{
fin=new FileInputStream("tn.txt");
System.out.println("Contents of the file :");
System.out.println("------------------------------------------");
// read the contents of a file using read() method
while((ch=fin.read())!=-1)
{
System.out.print((char)ch);
}
System.out.println();
}
catch(Exception e)
{
System.out.println("File does not exist...");
}
fin.close();
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
}
// Main method
public static void main(String[] a)throws Exception
{
System.out.println("=============================");
System.out.println("\tFile Retrieval using Byte Stream");
System.out.println("============================");
FileRead fr=new FileRead();
fr.disp();
System.out.println("-------------------------------------------------");
}
}

2. INPUT FILE
tn.txt
3. OUTPUT

CS9256 Web Technology IT-4/8-S Page 11 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
III.FILE RETRIEVAL USING BYTE ARRAY
1. SOURCE CODE
package files_bytes;
import java.io.*;
public class FileRead_for
{ FileInputStream fin;
int ch;
void disp()throws Exception
{
try
{
fin=new FileInputStream("tn.txt");
System.out.println("Contents of the file :");
System.out.println("-------------------------------------------------");
// return the file length using available() method
int size=fin.available();
System.out.println("File Length : "+size);
byte[] b=new byte[size];
// read the data into an array
fin.read(b);
for(int i=0;i<size;i++)
{
System.out.print((char)b[i]);
}
System.out.println();
}
catch(Exception e)
{
System.out.println("File does not exist...");
}
fin.close();
}
// Main method
public static void main(String[] a)throws Exception
{
System.out.println("==================================");
System.out.println("\tFile Retrieval using Byte Stream");
CS9256 Web Technology IT-4/8-S Page 12 of 63
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
System.out.println("===================================");
FileRead_for obj=new FileRead_for();
obj.disp();
System.out.println("-------------------------------------------------");
}
}

2. OUTPUT

CS9256 Web Technology IT-4/8-S Page 13 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
IV.FILE COPYING
1. SOURCE CODE
package files_bytes;
import java.io.*; public
class Filecopy {
/ Byte stream declarations
FileInputStream fin;
FileOutputStream fout;
int ch;
/ instance method()
public void copyf2f()throws Exception
{
try
{
// Byte stream definitions
fin=new
FileInputStream("C:\\Users\\GodShiva\\Documents\\NetBeansProjects\\WT_
Files\\src\\files_bytes\\IT.txt");
fout=new FileOutputStream("CSE.txt");
}
catch(FileNotFoundException e)
{
System.out.println("Input File is not found");
}
while((ch=fin.read())!=-1)
{
fout.write((char)ch);
}
// verify the end of the file using -1 success
code if(ch==-1)
System.out.println("File is copied successfully...\nSuccess Code :
"+ch);
fin.close();
fout.close();
}

CS9256 Web Technology IT-4/8-S Page 14 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
/ display the contents of a file
public void disp()throws Exception
{
try
{
fin=new FileInputStream("CSE.txt");
System.out.println("Contents of the file");
System.out.println("-------------------------------------------------");
while((ch=fin.read())!=-1)
{
System.out.print((char)ch);
}
System.out.println();
}
catch(FileNotFoundException e)
{
System.out.println("CSE Input File is not found");
}
}
public static void main(String[] args)throws Exception
{
System.out.println("===============================");
System.out.println("\tFile Copying using Byte Stream");
System.out.println("===============================");
Filecopy fc=new Filecopy();
fc.copyf2f();
fc.disp();
System.out.println("-------------------------------------------------");
}
}

2. INPUT FILE
SOURCE FILE : IT.txt
TARGET FILE : CSE.txt

CS9256 Web Technology IT-4/8-S Page 15 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
3. OUTPUT

CS9256 Web Technology IT-4/8-S Page 16 of 63


HANDLING PRIMITIVE TYPES
Existing problem
It is not possible to write the primitive types to file & read the primitive
types from file using FileOutputStream and FileInputStream class.
To overcome this problem, java uses the two popular filter classes like
DataOutputStream and DataInputStream (data stream)
Syntax
1. Writing data to file

// connect the file

FileOutputStream fout=new FileOutputStream(“ram.txt”);


// wrap the FileOutputStream in DataOutputStream

DataOutputStream dout=new DataOutputStream(fout);

2. Reading data from file

// connect the file

FileInputStream fin=new FileInputStream(“ram.txt”);

// wrap the FileOutputStream in DataOutputStream

DataInputStream din=new DataInputStream(fin);


CS9256 Web Technology IT-4/8-S Page 19 of 63
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
DATA OUTPUT STRAM
Complete class
Used to write the java primitive types to a file or standard input
system
Methods
1. writeUTF() : write string to file
2. writeInt() : write int data to file
3. writeFloat() : write float data to file
4. writeDouble() : write double to file
5. writeByte(int b) : write a byte to file
6. writeBoolean() : write boolean value to file
7. write(int c) : write a specified byte to file
8. writeShort() : write a short data to file
9. writeChar() : write a character to file
DATA INPUT STREAM
Complete class
Used to read the java primitive types from a file or standard
input system
Type of filtered class

CS9256 Web Technology IT-4/8-S Page 20 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
Methods
1. readUTF() : read string from file
2. readInt() : read int data from file
3. readFloat() : read float data from file
4. readDouble() : read double from file
5. readByte(int b) : read a byte from file
6. readBoolean() : read boolean value from file
7. read (int c) : read a specified byte from file
8. readShort() : read a short data from file
9. readChar() : read a character from file

VI. DATA INPUT & OUTPUT STREAM CLASSES


AIM
The aim of this java code is create a data file with employee
details using DataOutputStream class & accessing the contents of a
same file using DataInputStream class

1. SOURCE CODE
package files_bytes;
import java.io.*; public
class DataInOut {
public static void main(String[] args)throws Exception
{
System.out.println("==================================");
System.out.println("\tData Input & Output Stream Classes");
System.out.println("==================================");
// connect the file using file object
File fp=new File("prim.dat");
FileOutputStream fout=new FileOutputStream(fp.getName());
CS9256 Web Technology IT-4/8-S Page 21 of 63
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
DataOutputStream dout=new DataOutputStream(fout);
// Employee details
String name="laxman";
char blood='A';
int code=193;
double
pack=59000.50; try
{
/ write string to file
dout.writeUTF(name);
/ write int to file
dout.writeInt(code)
;
/ write character to file
dout.writeChar(blood);
/ write double to file
dout.writeDouble(pack);
fout.close();
dout.close();
System.out.println("File is created successfully ...");
/ open the file to access its contents
FileInputStream fin=new FileInputStream(fp.getName());
// wrap the FileInputStream in DataInputStream
DataInputStream din=new DataInputStream(fin);
System.out.println("Accessing File Data");
System.out.println("Employee Informations");
System.out.println("Name\t: "+din.readUTF());
System.out.println("Id\t: "+din.readInt());
System.out.println("Blood\t: "+din.readChar()+"+ive");
System.out.println("Money\t: "+din.readDouble());
fin.close();
din.close()
}
catch(Exception e)
{
System.out.println("Error in creating a file...");
}
CS9256 Web Technology IT-4/8-S Page 22 of 63
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
}
}

2. OUTPUT
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
III. SEQUENCE INPUT STREAM CLASS
It is used to read the data from more than one streams (multiple
Streams).
Syntax
SequenceInputStream ss=new SequenceInputStream(InputStream
s1, InputStream s2);

 Creates a new input stream by reading the data of


two input stream in order, first s1 and then s2.

VIII. EXAMPLE OF SEQUENCE INPUT STREAM CLASS


AIM
In this example, we are printing the data (contents) of two files
f1.txt & f2.txt
1. SOURCE CODE
package files;
import java.io.*;
public class SequenceInput {
public static void main(String[] args)throws Exception
{
System.out.println("====================================");
System.out.println("\t Sequence InputStream class");
System.out.println("====================================");
/ connect the mit.txt file using file input stream named f1
FileInputStream f1=new FileInputStream("mit.txt");
/ connect the mit.txt file using file input stream named f2
FileInputStream f2=new FileInputStream("ceg.txt");
/ connect the f1 & f2 to the constructor of sequence input stream class
SequenceInputStream ss=new SequenceInputStream(f1,f2);
System.out.println("Contents of the Two Files");
int ch;
/ read the contents of two files using read() method
while((ch=ss.read())!=-1)
CS9256 Web Technology IT-4/8-S Page 28 of 63
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
{
System.out.print((char)ch);
}
System.out.println();
}
}

2. INPUT FILES
1. mit.txt
Welcome to MIT campus, Anna University
MIT is a green campus of anna university.

2. ceg.txt
Welcome to CEG campus of Anna university.

CS9256 Web Technology IT-4/8-S Page 29 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
2. OUTPUT

CS9256 Web Technology IT-4/8-S Page 34 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
II. CHARACTER STREAMS

FILE WRITER CLASS



It is used to write textual information or character-oriented data to the
file.

It is derived from Writer class
Syntax
FileWriter fw=new FileWriter(“ram.txt”);
Various Builtin-Methods
1. write(String str)

Write the string to file

Return type : void

2. write(char str[])

Write a array of characters to file

Return type : void

3. write(int c)

Write a single character to file

Return type : void

Where,
c -> int specifying a character to be written
4. append(int c)

appends the specified character to the output writer

Return type : Writer

Where,
c -> the 16-bit character to append.
Drawbacks
It is not possible to write the line by line data.
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
XI. EXAMPLE OF FILE WRITER CLASS
1. SOURCE CODE
package files;
import java.io.*;
public class Fwriter {
public static void main(String[] args)throws Exception
{
System.out.println("==============================");
System.out.println("\tFile Writer class");
System.out.println("==============================");
// FileWriter creation
FileWriter fw=new FileWriter("ram.txt");
String str="Jai sri ram...";
/ Write strings to file using
write() fw.write(str);
/ close the file
fw.close();
System.out.println("File is created successfully...");
}
}

CS9256 Web Technology IT-4/8-S Page 36 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
2. OUTPUT

3. OUTPUT FILE
ram.txt

CS9256 Web Technology IT-4/8-S Page 37 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
FILE READER CLASS

It is used to read textual information or character-oriented data from
the file.

It is derived from Reader class
Syntax
FileReader fr=new FileReader(“ram.txt”);
Methods
1. read()

Reads a single character from file at a time

Return type : int

2. read(char[] buff)

reads characters into array

Return type : int

Drawbacks
It is not possible to read line by line data from a file
XII. EXAMPLE OF FILEREADER CLASS
1. SOURCE CODE
package files; import
java.io.*; public
class Freader {
public static void main(String[] args)throws Exception
{
System.out.println("==========================================");
System.out.println("\tFile Reader class");
System.out.println("==========================================");
FileReader fr;
int ch;
try
{
CS9256 Web Technology IT-4/8-S Page 38 of 63
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
/ connect the file by using the FileReader class
fr=new FileReader("mit.txt");
System.out.println("Contents of the file");
/ read the contents of a file by using read()
while((ch=fr.read())!=-1)
{
System.out.print((char)ch);
}
System.out.println();
fr.close();
}
catch(FileNotFoundException e)
{
System.out.println("File not found...");
}
}
}

CS9256 Web Technology IT-4/8-S Page 39 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
2. OUTPUT

BUFFERED READER CLASS


A FileWriter object is wrapped in a BufferedWriter class which makes
it possible to write strings to an output file
The BufferedWriter constructors require a FileWriter object.
The FileWriter object is created and then used in the constructor
for the BufferedWriter
Methods
1. read()

reads a single character

Return type : int

CS9256 Web Technology IT-4/8-S Page 45 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
2. readLine()

reads a line of text

Return type : String

3. read(char[] buf, int offset, int length)



reads characters into a portion of an array

Return type : int

4. close()

Closes the file & releases any resources associated with
the output stream

Return type : void

XIV. BUFFEREDREADER CLASS


1. SOURCE CODE
package files;
import java.io.*;
public class BuffReader {
public static void main(String[] args)throws IOException
{
System.out.println("============================");
System.out.println("\tBuffered Reader class");
CS9256 Web Technology IT-4/8-S Page 46 of 63
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
System.out.println("============================");
// connect the file using FileReader object
FileReader fr=new FileReader("ruby.txt");
BufferedReader br=new BufferedReader(fr);
String line;
int lc=0;
System.out.println("----------------------------------------------------");
System.out.println("Contents of the file");
System.out.println("----------------------------------------------------");
// get the contents by using readLine() method
while((line=br.readLine())!=null)
{
System.out.println(line);
lc++;
}
System.out.println("Total Lines Detected \t: "+lc);
}
}

CS9256 Web Technology IT-4/8-S Page 47 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
2. OUTPUT

BUFFERED WRITER CLASS


Methods
1. write(char c)
 Writes a single character

Return type : void
2. write(char[] buf, int offset, int length)

Writes a portion of a character array, beginning at the
offset and writing length number of characters

Return type : void

CS9256 Web Technology IT-4/8-S Page 48 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
3. write(String s, int offset, int length)

Writes a portion of a string, beginning at the offset
character. Writies length number of charcaters

Return type : void
4. newline()

Writes a line separator into the output stream

Return type : void

5. close()

Closes the file & releases any resources associated with
the output stream

Return type : void
XV. APPENDING TEXT TO FILE USING BUFFERED WRITER
1. SOURCE CODE
package files;
import java.io.*;
public class BuffWriter {
public static void main(String[] args)throws Exception
{
String text="Welcome to Tamil Nadu";
/ connect the file using file object
File fp=new File("tamil.txt");
/ connect
FileWriter fw=new FileWriter(fp.getName());
/ wrap the file writer to buffered writer
BufferedWriter bw=new BufferedWriter(fw);
try
{
/ verify the file using exist()
if(fp.exists()==false)
{
/ create a new empty file
CS9256 Web Technology IT-4/8-S Page 49 of 63
nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
fp.createNewFile();
}
/ append the text
bw.write(text);
/ close the file
bw.close();
System.out.println("File is created successfully at\n"+fp.getAbsolutePath());
}
catch(Exception e)
{
System.out.println("Error in Writing a file...");
}
}

2. OUTPUT FILE

CS9256 Web Technology IT-4/8-S Page 50 of 63


nd
Java I/O [Files, Directories] [ 2 Year IT-4/8-S & R]
3. OUTPUT

CS9256 Web Technology IT-4/8-S Page 62 of 63

You might also like