Cse 310 Assignment : 4 Introduction and Definition

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 10

CSE 310 ASSIGNMENT

(FILE HANDLING IN JAVA)

Name of Student: HITESH SAHANI


Registration Number:11816118
Section: MS
Roll No: 18 (G1)

Problem No. Assigned: 4

Introduction and definition


File handling deals to working with the file in java. Writing and Reading into java files is called
as file handling in java. The File like container that can contain different types of information.
The file can contain text, images, videos, tables, and more.

In Java, File class is used to enables us to work with different types of files. File class is a
member of the java.io packages. Java provides different methods to read, write, update & delete
files

Different types of operation which can be performed on a file is given below:

 creating a file
 updating a file

 deleting a file

 uploading a file to specific location

 opening a file

 closing a file
 Syntax:

In the below-given syntax, package java.io is imported into the program to work with the
file. java.io package exposes a File class that can be initiated by referencing the file to
the constructor of File class.

//importing file class


import java.io.File;
//File name passed to the object
File fileObj = new File("file.txt");

working of file handling in java

In Java, File handling is taken place by concepts of streaming. Input/Output operations on a file
perform through the streaming. Stream refers to a sequence of data.

In java, Stream is of two types:

 Character Stream: A stream that takes place with the characters is known as a character
stream. Processing of the data takes place with the stream of characters in the files.

 Byte Stream: A stream that takes place with the byte data is known as a byte stream.
Processing of the data takes place with the stream of bytes in the files
File Handling Methods

Some of the methods are given below for performing different operations in java:

1. createNewFile(): createNewFile method used to create an empty file. It returns the


response as boolean.
2. getName(): This method is used to get the file name. It returns the string i.e. name of the
file in response.
3. getAbsolutePath(): It returns the absolute path of the file. The return type of this method
is a string.
4. canRead(): This method used to check whether the file is readable or not. It returns a
boolean value.
5. canWrite(): This method used to check whether the file is writable or not. It returns a
boolean value.
6. delete(): This method used in deleting a file. It returns a boolean value.
7. exists(): This method used to check whether a file exists or not. It returns a boolean
value.
8. length(): This method returns the size of the file in bytes. The return type of this method
is long.
9. list(): This method returns an array of the files available in the directory. It returns an
array of string values.
10. mkdir(): This method is used to create a directory. It returns a boolean value.

File handling in Java----------------------


Two categories of File System Operations

i) High level operations / External operations

Create a folder

delete a folder

create a text file

delete a text file etc...

ii) Low level operations / Internal operations

Read data
Write data etc...
------------------------
Using File Class we can perform High level operations
Examples:
1) Create a Folder
package javaiooperations;

.File;

public class CreateFolder {

public static void main(String [] args){


File fileObject = new File("C:/Users/G C Reddy/Desktop/Selenium");
fileObject.mkdir();
}
}
---------------------------------
2) Check the existence of Selenium Folderpublic static void main(String [] args){
File fileObject = new File("C:/Users/G C Reddy/Desktop/UFT");
boolean a = fileObject.exists();
System.out.println(a);
}
-------------------------------------
3) Delete a Folder
public static void main(String [] args){
File abc = new File ("C:/Users/G C Reddy/Desktop/Selenium");
abc.delete();
boolean a = abc.exists();
//System.out.println(a);
if (a == true) {
System.out.println("Folder exists");
}
else{
System.out.println("Folder doesn't exist");
}
}
-----------------------------------
4) Create a Text file
public class CreateFolder {

public static void main(String [] args){


File abc = new File ("C:/Users/G C Reddy/Desktop/Selenium.txt");
try {
abc.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
-------------------------------------------
5) Delete a text file public static void main(String [] args){
File abc = new File ("C:/Users/G C Reddy/Desktop/Selenium.txt");
abc.delete();

Below are examples of File Handling in Java:

Example #1

In this example, we can see how different methods are used in the program to get the specified
details. In this application, different methods are using to get information related to file such as:

1. Retrieving the absolute path of the file.


2. Checking whether the file is writable or not.
3. Checking whether the file is readable or not.
4. Retrieving file name.
5. Retrieving file size.
6. Retrieving list of files available to the specified directory etc.

Code:

Importing io package different classes.

import java.io.File;
import java.io.IOException;
public class FileHandlingExample2 {
public static void main(String[] args) {
// Creating an object of a file
File fileObj = new File("D:/Programs/fileHandlingOperations.txt");
if (fileObj.exists()) {
//retrieving the path of the specified file
System.out.println("\nSpecified file path: " + fileObj.getAbsolutePath());
//checking whether the file is writable or not
System.out.println("\nIs the file Writable: " + fileObj.canWrite());
//checking whether the file is Readable or not
System.out.println("\nIs the file Readable " + fileObj.canRead());
//retrieving file name
System.out.println("\nFile name: " + fileObj.getName());
//retrieving file size
System.out.println("\nFile size (in bytes) " + fileObj.length());
File fileDirObj = new File("D:/Programs/");
String[] fileList = fileDirObj.list();
//displaying here the list of files available in the directory
for (int i = 0; i < fileList.length; i++) {
System.out.print("\n" + fileList[i]);
}
System.out.println("\n");
}
else {
System.out.println("Specified file does not exist.");
}
}
}

Output:

In the above-given example, we can see how different methods are providing the information
needed to perform the different checks related to files

Example #2

In this example, we can see how different methods are being used in the program for different
types of operation. exists() method using in the program to check if file exists are not, After that
if else.. condition is placed.

In the If condition, it checks first whether the existing file is writable or not. If the existing file
remains writable then code block under if section used File Writer class method to write content
into the existing file.

Code:

Importing io package different classes.


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileHandlingExample {
public static void main(String[] args) {
try {
File fileObj = new File("D:/Programs/fileHandlingOperations.txt");
if(fileObj.exists()){
System.out.println("File already exists.");
if(fileObj.canWrite()){
//creating object of FileWriter class to write things on file
FileWriter fwObj = new FileWriter("D:/Programs/fileHandlingOperations.txt");
// Writes this content into the specified file
fwObj.write("It is a basic example of writing in file!");
//closing the files once writing completed
fwObj.close();
System.out.println("\nContent has been written to the file.");
}else{
System.out.println("\nFile is not in writable mode.");
}
;
}else{
if (fileObj.createNewFile()) {
System.out.println("New File created: " + fileObj.getName());
}
}
}
catch (IOException ioError) {
System.out.println("An error occurred.");
ioError.printStackTrace();
}
}
}

Output:

In the above-given example, After compilation, running the program first time will create a file
with the specified name in the program.

Running program second time will write the content in the already existing file.
 

Conclusion
In the above, we discussed about what is a file, its methods, importance and
operation that can be performed on a file and how file handling works in java
programming language. It was also demonstrated in the above section about
classes & methods that can be used to work with files in java.

Write a java program that creates an object of Loan class and stores it
in a file named output, read the Loan object from the file output and
display total loan amount.

code

import java.io.*;

 class Loan implements Serializable {


  private static final long serialVersionUID = 1L;
private double loan_amount;
Loan(double loan_amount)
{
this.loan_amount=loan_amount;
}
public String toString() {
return "Loan Amount:" + loan_amount ;
}
}
 public class scheme{
public static void main(String[] args)  throws IOException  
{
Loan l1=new Loan(125000);

try {
FileOutputStream f=new FileOutputStream(new File("output.txt"));
ObjectOutputStream o=new ObjectOutputStream(f);
o.writeObject(l1);
o.close();
f.close();

FileInputStream fi= new FileInputStream(new File("output.txt"));


ObjectInputStream oi=new ObjectInputStream(fi);

Loan lr1=(Loan) oi.readObject();

System.out.println(lr1.toString());

oi.close();
fi.close();

} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

output

You might also like