0% found this document useful (0 votes)
28 views16 pages

Adarsh 11

Uploaded by

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

Adarsh 11

Uploaded by

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

Welcome

OBJECT ORIENTED PROGRAMMING

Topic name: File Handling


File Handling

In Java,With the help of File Class ,we can work with files,this files
class is inside the java.io package.File class can be used by creating
an object of the class and then specifying the name of the file.

Why File Handling is Required?


 File Handling is an integral part of any programming language as file
handling enables us to store the output of any particular program in a
file and allows us to perform certain operations on it.
 In simple words, file handling means reading and writing data to a
file.
File class

 Java file class is java’s representation of file or directory


pathname.
 Java file class contains several methods for working with
the pathname,deleting and renaming files,creating new
directories,listening the contents of a directory and
determining several common attributes of files and
directories.
 Below are the some of the examples of Methods of file class.
File Class methods:
Method Name Description Return Type

It tests whether the file is


canRead() Boolean
readable or not.

It tests whether the file is


canWrite() Boolean
writable or not.

createNewFile() It creates an empty file. Boolean

delete() It deletes a file. Boolean


It tests whether the file
exists() Boolean
exists or not.
Returns the size of the file
length() Long
in bytes.
Returns the name of the
getName() String
file.

Returns an array of the


list() String[]
files in the directory.

mkdir() Creates a new directory. Boolean

Returns the absolute


getAbsolutePath() String
pathname of the file.
File operations in Java

The following are the several operations that can be


performed on a file in Java :

 Create a File
 Read from a File
 Write to a File
 Delete a File
//Creating a file

import java.io.File;
Import java.io.IOException;

class GFG {
public static void main(String[] args)
{
try{

File exp = new File("myfile.txt");


if(exp.createNewfile()){
System.out.println("File Created!“+exp.getName());
}
else{
System.out.println("File already exists);
}
} catch(IOException e) {
System.out.println(“error occurred”);
e.printStackTrace();
}
}
}
//reading from a file
import java.io.File;
Import java.io.IOException;
Import java.util.Scanner;

class GFG {
public static void main(String[] args)
{
try{

File exp = new File("myfile.txt");


Scanner reader=new Scanner(exp);
while(reader.hasNextLine()){
String data=reader.nextLine();
System.out.println(data);
}
reader.close();
}
catch(IOException e) {
System.out.println(“error occurred”);
e.printStackTrace();
}
}
}
//write to a file

import java.io.FileWriter;

// Import the IOException class for handling errors


import java.io.IOException;

public class GFG {


public static void main(String[] args)
{
try {
FileWriter Writer = new FileWriter("myfile.txt");
Writer.write(
"Files in Java are seriously good!!");
Writer.close();
System.out.println("Successfully written.");
}
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
//deleting a file

import java.io.File;

public class GFG {


public static void main(String[] args)
{
File Obj = new File("myfile.txt");
if (Obj.delete()) {
System.out.println("The deleted file is : "
+ Obj.getName());
}
else {
System.out.println(
"Failed in deleting the file.");
}
}
}
File Writer

 This class inherits from the OutputStream class.

 The constructors of this class assume that the default character


encoding and the default byte-buffer size are acceptable. To
specify these values yourself, construct an OutputStreamWriter
on a FileOutputStream.

 FileWriter is meant for writing streams of characters. For


writing streams of raw bytes, consider using a
FileOutputStream.
 FileWriter creates the output file if it is not present already.
Methods of file writer

 public void write (int c) throws IOException – Writes a single


character.
 public void write (char [] stir) throws IOException – Writes an array
of characters.
 public void write(String str)throws IOException – Writes a string.
 public void write(String str, int off, int len)throws IOException
– Writes a portion of a string. Here off is offset from which to start
writing characters and len is the number of characters to write.
 public void flush() throws IOException flushes the stream
 public void close() throws IOException flushes the stream first and
then closes the writer.
//creating a text file using filewriter
import java.io.FileWriter;
import java.io.IOException;
class CreateFile
{
public static void main(String[] args) throws IOException
{
// Accept a string
String str = "File Handling in Java using "+
" FileWriter and FileReader";

// attach a file to FileWriter


FileWriter fw=new FileWriter("output.txt");

// read character wise from string and write


// into FileWriter
for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));

System.out.println("Writing successful");
//close the file
fw.close();
}
}
File Reader

 FileReader is useful to read data in the form of characters from a ‘text’ file.

 This class inherited from the InputStreamReader Class.

 The constructors of this class assume that the default character encoding and
the default byte-buffer size are appropriate. To specify these values yourself,
construct an InputStreamReader on a FileInputStream.

 FileReader is meant for reading streams of characters. For reading streams


of raw bytes, consider using a FileInputStream.
Methods of file reader :

 public int read () throws IOException – Reads a single character. This method will
block until a character is available, an I/O error occurs, or the end of the stream is reached.
 public int read(char[] cbuff) throws IOException – Reads characters into an array. This
method will block until some input is available, an I/O error occurs, or the end of the
stream is reached.
 public abstract int read(char[] buff, int off, int len) throws IOException –Reads
characters into a portion of an array. This method will block until some input is available,
an I/O error occurs, or the end of the stream is reached.
Parameters:
cbuf – Destination buffer
off – Offset at which to start storing characters
len – Maximum number of characters to read
 public void close() throws IOException closes the reader.
 public long skip(long n) throws IOException –Skips characters. This method will block
until some characters are available, an I/O error occurs, or the end of the stream is
reached.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
public static void main(String[] args) throws IOException
{
// variable declaration
int ch;

// check if File exists or not


FileReader fr=null;
try
{
fr = new FileReader("text");
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
}

// read from FileReader till the end of file


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

// close the file


fr.close();
}
}
T
h Y
a o
n u
k

You might also like