You are on page 1of 19

File IO Operations

Course Code: CSE2103 Course Title: Object Oriented Programming

Dept. of Computer Science


School of Science and Technology

Lecturer No: 19 Week No: 10 Semester: Spring 2022


Lecturer: Dr. M Ashikur Rahman
Lecture Outline

1. File Class
2. Methods of File Class
3. File Write Operation
4. File Read Operation
Check the Error
1. .
2. .
3. public class File{
4. public Static void main (string [] args) {
5. File file = new File(“filename.txt”);
6. If(file.exists()) {
7. System.out.Println(“File exists”);
8. } {
9. System.out.println(“File does not exist”);
10. try {
11. file.createNewFile();
12. } catch (IOException ) {
13. e.printStackTrace();
14. }
15. }
16. }
17. }
File IO

• The File class from the java.io package, allows us to


work with files.

• To use the File class, create an object of the class, and


specify the filename or directory name:

import java.io.File; // Import the File class


File Obj = new File("filename.txt"); // Specify the
filename
File IO
Methods of File Class

Method Type Description

canRead() Boolean Tests whether the file is readable or not

canWrite() Boolean Tests whether the file is writable or not

createNewFile() Boolean Creates an empty file

delete() Boolean Deletes a file

exists() Boolean Tests whether the file exists

getName() String Returns the name of the file

getAbsolutePath() String Returns the absolute pathname of the file

length() Long Returns the size of the file in bytes

list() String[] Returns an array of the files in the directory

mkdir() Boolean Creates a directory


1. import java.io.File;
2. import java.io.IOException;
3. Public class FileName{
4. Public static void main (String [] args) {
5. File oldFile = new File(“Old _filename.txt”);
File newFile = new File(“New _filename.txt”);
Boolean Renamed = old.renameTo(newFile);
1. If(Renamed) {
2. System.out.println(Old file +”renamed to” +newFile);
3. } else {
4. System.out.println(“”Renaming” +old file ); }
5. }
6. }
Creating file

• To create a file in Java, you can use the


createNewFile() method.
• This method returns a boolean value:
true if the file was successfully created, and
false if the file already exists.
• The method is enclosed in a try...catch block.
• This is necessary because it throws an IOException if an
error occurs (if the file cannot be created for some
reason)
1. import java.io.File;
2. implot java.io.IOException;
3. Public class File{
4. Public static void main (String [] args) {
5. File file = new File(“filename.txt”);
6. If(file.exists()) {
7. System.out.println(“File exists”);
8. } else {
9. System.out.println(“File does not exist”);
10. try {
11. file.createNewFile();
12. } catch (IOException e) {
13. e.printStackTrace();
14. }
15. }
16. }
17. }
Creating file

• To create a file in a specific directory (requires


permission), specify the path of the file and use double
backslashes to escape the "\" character.

• File myObj = new File("C:\\Users\\MyName\\filename.txt");


import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to
handle errors

public class CreateFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Reading from File

• We create object of FileReader class to read some


text from a file we created.
• We create BufferedReader object using the
FileReader class object to read the file content.
• Note that when you are done reading to the file, you
should close it with the close() method
import java.io.File; // Import the File class
import java.io.FileNotFoundException; //Import to handle errors
import java.util.Scanner; // Import the Scanner to read text files

public class ReadFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Writing in File

• We use the FileWriter class together with its write()


method to write some text to the file we created.
• Note that when you are done writing to the file, you
should close it with the close() method
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to
handle errors

public class WriteToFile {


public static void main(String[] args) {
try {
FileWriter Writer = new FileWriter("filename.txt");
Writer.write("Files in Java might be tricky");
Writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Find the output

package com.javatpoint;
import java.io.*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Write a program to read from a file and
write to a file.
Books

1. Java Complete Reference, 7th Edition, By Herbert Schildt.

2. A Programmer's Guide to Java SE 8 Oracle Certified Associate, Khalid A. MughalRolf W.


Rasmussen

3. Java How to Program Java, 9th Edition, By Deitel and Deitel.

4. The Java Language Specification, By J. Gosling, B. Joy, G. Steele, G.Bracha and A.


Buckley

5. Introduction to Programming Using Java, 6th Edition, By David j. Eck

6. Head First Java, By Kathy Sierra and Bert Bates


References

1. Java Complete Reference, 7th Edition, By Herbert Schildt.

1. A Programmer's Guide to Java SE 8 Oracle Certified Associate, Khalid A.


MughalRolf W. Rasmussen

1. The Java Tutorials. http://docs.oracle.com/javase/tutorial/

1. https://www.w3schools.com/java/java_files_create.asp

You might also like