SlideShare a Scribd company logo
File Operations in Java
In Java, a File is an abstract data type. A named location used to store related information is known as a File. There are several File
Operations like creating a new File, getting information about File, writing into a File, reading from a File and deleting a File.
Before understanding the File operations, it is required that we should have knowledge of Stream and File methods. If you have
knowledge about both of them, you can skip it.
Stream
A series of data is referred to as a stream. In Java, Stream is classified into two types, i.e., Byte Stream and Character Stream.
File Operations
We can perform the following operation on a file:
o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File
Byte Stream
Byte Stream is mainly involved with byte data. A file handling process with a byte stream is a process in which an input is provided
and executed with the byte data.
Character Stream
Character Stream is mainly involved with character data. A file handling process with a character stream is a process in which an
input is provided and executed with the character data.
To get more knowledge about the stream, click here.
Java File Class Methods
S.No. Method Return
Type
Description
1. canRead() Boolean The canRead() method is used to check whether we can read the data of the file or
not.
2. createNewFile() Boolean The createNewFile() method is used to create a new empty file.
3. canWrite() Boolean The canWrite() method is used to check whether we can write the data into the file
or not.
4. exists() Boolean The exists() method is used to check whether the specified file is present or not.
5. delete() Boolean The delete() method is used to delete a file.
6. getName() String The getName() method is used to find the file name.
7. getAbsolutePath() String The getAbsolutePath() method is used to get the absolute pathname of the file.
8. length() Long The length() method is used to get the size of the file in bytes.
9. list() String[] The list() method is used to get an array of the files available in the directory.
10. mkdir() Boolean The mkdir() method is used for creating a new directory.
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();
}
}
}
Write To a File
In the following example, we use the FileWriter class together with its write() method to write some text to the file we
created in the example above. Note that when you are done writing to the file, you should close it with
the close() method:
Example
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 myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Read a File
In the previous chapter, you learned how to create and write to a file.
In the following example, we use the Scanner class to read the contents of the text file we created in the previous
chapter:
Example
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class 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();
}
}
}
Get File Information
To get more information about a file, use any of the File methods:
Example
import java.io.File; // Import the File class
public class GetFileInfo {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}
Delete a File
To delete a file in Java, use the delete() method:
Example
import java.io.File; // Import the File class
public class DeleteFile {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
Delete a Folder
You can also delete a folder. However, it must be empty:
Example
import java.io.File;
public class DeleteFolder {
public static void main(String[] args) {
File myObj = new File("C:UsersMyNameTest");
if (myObj.delete()) {
System.out.println("Deleted the folder: " + myObj.getName());
} else {
System.out.println("Failed to delete the folder.");
}
}
}

More Related Content

Similar to FileHandling.docx

Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12Vince Vo
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
Eduardo Bergavera
 
import required package file import java.io.File; The Filed.pdf
 import required package file import java.io.File; The Filed.pdf import required package file import java.io.File; The Filed.pdf
import required package file import java.io.File; The Filed.pdf
anandinternational01
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3sotlsoc
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
NguynThiThanhTho
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
PragatiSutar4
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
secunderbadtirumalgi
 
Chapter 5 Class File
Chapter 5 Class FileChapter 5 Class File
Chapter 5 Class File
Khirulnizam Abd Rahman
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
File Input and Output in Java Programing language
File Input and Output in Java Programing languageFile Input and Output in Java Programing language
File Input and Output in Java Programing language
BurhanKhan774154
 
Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2
Martijn Verburg
 
Know how to redirect input and output- and know how to append to an ex.docx
Know how to redirect input and output- and know how to append to an ex.docxKnow how to redirect input and output- and know how to append to an ex.docx
Know how to redirect input and output- and know how to append to an ex.docx
wkelli
 
working with files
working with filesworking with files
working with files
SangeethaSasi1
 

Similar to FileHandling.docx (20)

IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
import required package file import java.io.File; The Filed.pdf
 import required package file import java.io.File; The Filed.pdf import required package file import java.io.File; The Filed.pdf
import required package file import java.io.File; The Filed.pdf
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
My History
My HistoryMy History
My History
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
 
Chapter 5 Class File
Chapter 5 Class FileChapter 5 Class File
Chapter 5 Class File
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files in c++
Files in c++Files in c++
Files in c++
 
File Input and Output in Java Programing language
File Input and Output in Java Programing languageFile Input and Output in Java Programing language
File Input and Output in Java Programing language
 
History
HistoryHistory
History
 
Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2
 
Know how to redirect input and output- and know how to append to an ex.docx
Know how to redirect input and output- and know how to append to an ex.docxKnow how to redirect input and output- and know how to append to an ex.docx
Know how to redirect input and output- and know how to append to an ex.docx
 
working with files
working with filesworking with files
working with files
 
Java Week4(A) Notepad
Java Week4(A)   NotepadJava Week4(A)   Notepad
Java Week4(A) Notepad
 
File handling
File handlingFile handling
File handling
 

Recently uploaded

The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
MuhammadTufail242431
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
Kamal Acharya
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
DuvanRamosGarzon1
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
Kamal Acharya
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 

Recently uploaded (20)

The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 

FileHandling.docx

  • 1. File Operations in Java In Java, a File is an abstract data type. A named location used to store related information is known as a File. There are several File Operations like creating a new File, getting information about File, writing into a File, reading from a File and deleting a File. Before understanding the File operations, it is required that we should have knowledge of Stream and File methods. If you have knowledge about both of them, you can skip it. Stream A series of data is referred to as a stream. In Java, Stream is classified into two types, i.e., Byte Stream and Character Stream. File Operations We can perform the following operation on a file: o Create a File o Get File Information o Write to a File o Read from a File o Delete a File
  • 2.
  • 3. Byte Stream Byte Stream is mainly involved with byte data. A file handling process with a byte stream is a process in which an input is provided and executed with the byte data.
  • 4. Character Stream Character Stream is mainly involved with character data. A file handling process with a character stream is a process in which an input is provided and executed with the character data. To get more knowledge about the stream, click here. Java File Class Methods S.No. Method Return Type Description 1. canRead() Boolean The canRead() method is used to check whether we can read the data of the file or not. 2. createNewFile() Boolean The createNewFile() method is used to create a new empty file. 3. canWrite() Boolean The canWrite() method is used to check whether we can write the data into the file or not. 4. exists() Boolean The exists() method is used to check whether the specified file is present or not. 5. delete() Boolean The delete() method is used to delete a file. 6. getName() String The getName() method is used to find the file name. 7. getAbsolutePath() String The getAbsolutePath() method is used to get the absolute pathname of the file.
  • 5. 8. length() Long The length() method is used to get the size of the file in bytes. 9. list() String[] The list() method is used to get an array of the files available in the directory. 10. mkdir() Boolean The mkdir() method is used for creating a new directory. 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.");} }
  • 6. } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } } Write To a File In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you are done writing to the file, you should close it with the close() method: Example import java.io.FileWriter; // Import the FileWriter class import java.io.IOException; // Import the IOException class to handle errors public class WriteToFile {
  • 7. public static void main(String[] args) { try { FileWriter myWriter = new FileWriter("filename.txt"); myWriter.write("Files in Java might be tricky, but it is fun enough!"); myWriter.close(); System.out.println("Successfully wrote to the file."); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } } Read a File In the previous chapter, you learned how to create and write to a file.
  • 8. In the following example, we use the Scanner class to read the contents of the text file we created in the previous chapter: Example import java.io.File; // Import the File class import java.io.FileNotFoundException; // Import this class to handle errors import java.util.Scanner; // Import the Scanner class 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) {
  • 9. System.out.println("An error occurred."); e.printStackTrace(); } } } Get File Information To get more information about a file, use any of the File methods: Example import java.io.File; // Import the File class public class GetFileInfo { public static void main(String[] args) { File myObj = new File("filename.txt"); if (myObj.exists()) { System.out.println("File name: " + myObj.getName());
  • 10. System.out.println("Absolute path: " + myObj.getAbsolutePath()); System.out.println("Writeable: " + myObj.canWrite()); System.out.println("Readable " + myObj.canRead()); System.out.println("File size in bytes " + myObj.length()); } else { System.out.println("The file does not exist."); } } } Delete a File To delete a file in Java, use the delete() method: Example import java.io.File; // Import the File class
  • 11. public class DeleteFile { public static void main(String[] args) { File myObj = new File("filename.txt"); if (myObj.delete()) { System.out.println("Deleted the file: " + myObj.getName()); } else { System.out.println("Failed to delete the file."); } } } Delete a Folder You can also delete a folder. However, it must be empty: Example import java.io.File;
  • 12. public class DeleteFolder { public static void main(String[] args) { File myObj = new File("C:UsersMyNameTest"); if (myObj.delete()) { System.out.println("Deleted the folder: " + myObj.getName()); } else { System.out.println("Failed to delete the folder."); } } }