SlideShare a Scribd company logo
Random Class
&
File Handling in Java
The Random Class
• Some methods of the Random class:
Java Foundations, 4th Edition, Lewis/DePasquale/Chase 3 - 2
//********************************************************************
// RandomNumbers.java Java Foundations
//
// Demonstrates the creation of pseudo-random numbers using the
// Random class.
//********************************************************************
import java.util.Random;
public class RandomNumbers
{
//-----------------------------------------------------------------
// Generates random numbers in various ranges.
//-----------------------------------------------------------------
public static void main(String[] args)
{
Random generator = new Random();
int num1;
float num2;
num1 = generator.nextInt();
System.out.println("A random integer: " + num1);
Java Foundations, 4th Edition, Lewis/DePasquale/Chase 3 - 3
num1 = generator.nextInt(10) + 1;
System.out.println("From 1 to 10: " + num1);
num1 = generator.nextInt(15) + 20;
System.out.println("From 20 to 34: " + num1);
num1 = generator.nextInt(20) - 10;
System.out.println("From -10 to 9: " + num1);
num2 = generator.nextFloat();
System.out.println("A random float (between 0-1): " + num2);
num2 = generator.nextFloat() * 6; // 0.0 to 5.999999
num1 = (int)num2 + 1;
System.out.println("From 1 to 6: " + num1);
}
}
Java Foundations, 4th Edition, Lewis/DePasquale/Chase 3 - 4
Java File Handling
• 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 myObj = new File("filename.txt"); // Specify the filename
File Methods
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
Create a File
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");
myObj.createNewFile();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Write To a File
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();
}
}
}
Java Read Files
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();
}
}
}
Delete a File
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.");
}
}
}

More Related Content

Similar to Random Class & File Handling.pptx

JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)
Prof. Erwin Globio
 
Class loader basic
Class loader basicClass loader basic
Class loader basic
명철 강
 
Writing documentation with Asciidoctor
Writing documentation  with  AsciidoctorWriting documentation  with  Asciidoctor
Writing documentation with Asciidoctor
Jérémie Bresson
 
Code to copy Person.java .pdf
Code to copy Person.java .pdfCode to copy Person.java .pdf
Code to copy Person.java .pdf
anokhijew
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
DEVTYPE
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
CODE WHITE GmbH
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptx
madan r
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
Suman Astani
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
People Strategists
 
In Java- Create a Graduate class derived from Student- A graduate has.pdf
In Java- Create a Graduate class derived from Student- A graduate has.pdfIn Java- Create a Graduate class derived from Student- A graduate has.pdf
In Java- Create a Graduate class derived from Student- A graduate has.pdf
Stewart29UReesa
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
NguynThiThanhTho
 
FileHandling.docx
FileHandling.docxFileHandling.docx
FileHandling.docx
NavneetSheoran3
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
DevaKumari Vijay
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
Vince 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
 
We will be making 4 classes Main - for testing the code Hi.pdf
 We will be making 4 classes Main - for testing the code Hi.pdf We will be making 4 classes Main - for testing the code Hi.pdf
We will be making 4 classes Main - for testing the code Hi.pdf
anithareadymade
 

Similar to Random Class & File Handling.pptx (20)

JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)
 
Class loader basic
Class loader basicClass loader basic
Class loader basic
 
Writing documentation with Asciidoctor
Writing documentation  with  AsciidoctorWriting documentation  with  Asciidoctor
Writing documentation with Asciidoctor
 
Code to copy Person.java .pdf
Code to copy Person.java .pdfCode to copy Person.java .pdf
Code to copy Person.java .pdf
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptx
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
In Java- Create a Graduate class derived from Student- A graduate has.pdf
In Java- Create a Graduate class derived from Student- A graduate has.pdfIn Java- Create a Graduate class derived from Student- A graduate has.pdf
In Java- Create a Graduate class derived from Student- A graduate has.pdf
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
 
FileHandling.docx
FileHandling.docxFileHandling.docx
FileHandling.docx
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
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
 
We will be making 4 classes Main - for testing the code Hi.pdf
 We will be making 4 classes Main - for testing the code Hi.pdf We will be making 4 classes Main - for testing the code Hi.pdf
We will be making 4 classes Main - for testing the code Hi.pdf
 

More from VijalJain3

CN - Lecture 2.pptx
CN - Lecture 2.pptxCN - Lecture 2.pptx
CN - Lecture 2.pptx
VijalJain3
 
1. Introduction to Cyber Security.pptx
1. Introduction to Cyber Security.pptx1. Introduction to Cyber Security.pptx
1. Introduction to Cyber Security.pptx
VijalJain3
 
Recursion.pptx
Recursion.pptxRecursion.pptx
Recursion.pptx
VijalJain3
 
RSA.pptx
RSA.pptxRSA.pptx
RSA.pptx
VijalJain3
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
VijalJain3
 
AES.pptx
AES.pptxAES.pptx
AES.pptx
VijalJain3
 

More from VijalJain3 (6)

CN - Lecture 2.pptx
CN - Lecture 2.pptxCN - Lecture 2.pptx
CN - Lecture 2.pptx
 
1. Introduction to Cyber Security.pptx
1. Introduction to Cyber Security.pptx1. Introduction to Cyber Security.pptx
1. Introduction to Cyber Security.pptx
 
Recursion.pptx
Recursion.pptxRecursion.pptx
Recursion.pptx
 
RSA.pptx
RSA.pptxRSA.pptx
RSA.pptx
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
AES.pptx
AES.pptxAES.pptx
AES.pptx
 

Recently uploaded

Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball playEric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
enizeyimana36
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
mamunhossenbd75
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
mamamaam477
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
Recycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part IIRecycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part II
Aditya Rajan Patra
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
IJNSA Journal
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
Rahul
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 

Recently uploaded (20)

Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball playEric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
Recycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part IIRecycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part II
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 

Random Class & File Handling.pptx

  • 2. The Random Class • Some methods of the Random class: Java Foundations, 4th Edition, Lewis/DePasquale/Chase 3 - 2
  • 3. //******************************************************************** // RandomNumbers.java Java Foundations // // Demonstrates the creation of pseudo-random numbers using the // Random class. //******************************************************************** import java.util.Random; public class RandomNumbers { //----------------------------------------------------------------- // Generates random numbers in various ranges. //----------------------------------------------------------------- public static void main(String[] args) { Random generator = new Random(); int num1; float num2; num1 = generator.nextInt(); System.out.println("A random integer: " + num1); Java Foundations, 4th Edition, Lewis/DePasquale/Chase 3 - 3
  • 4. num1 = generator.nextInt(10) + 1; System.out.println("From 1 to 10: " + num1); num1 = generator.nextInt(15) + 20; System.out.println("From 20 to 34: " + num1); num1 = generator.nextInt(20) - 10; System.out.println("From -10 to 9: " + num1); num2 = generator.nextFloat(); System.out.println("A random float (between 0-1): " + num2); num2 = generator.nextFloat() * 6; // 0.0 to 5.999999 num1 = (int)num2 + 1; System.out.println("From 1 to 6: " + num1); } } Java Foundations, 4th Edition, Lewis/DePasquale/Chase 3 - 4
  • 5. Java File Handling • 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 myObj = new File("filename.txt"); // Specify the filename
  • 6. File Methods 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
  • 7. Create a File 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"); myObj.createNewFile(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
  • 8. Write To a File 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(); } } }
  • 9. Java Read Files 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(); } } }
  • 10. Delete a File 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."); } } }