In this core java training session, you will learn Examples of File IO &
Introduction to JDBC. Topics covered in this session are:
• File IO Continued
• Intro to JDBC (Java Database Connectivity)
For more information about this course visit on this link: https://www.mindsmapped.com/courses/software-development/learn-java-fundamentals-hands-on-training-on-core-java-concepts/
File Handling Presentation As well as File handling code in java Update, Delete, Search, View, Insert in file code are available in this presentation in you face some issues so contact me 03244064060 , Also in my Email: azeemaj101@gmail.com and Twitter @azeemaj101
Exceptions, I/O and Threads Input and Output in Java: The File Class, Standard Streams, Keyboard
Input, File I/O Using Byte Streams, Character Streams, File I/O Using Character Streams -
Buffered Streams, File I/O Using a Buffered Stream, Keyboard Input Using a Buffered Stream,Writing Text Files. Threads: Threads vs. Processes, Creating Threads by Extending Thread,
Creating Threads by Implementing Runnable, Advantages of Using Threads, Daemon Threads,
Thread States, Thread Problems, Synchronization. Exceptions: Exception Handling, The Exception
Hierarchy, throws statement, throw statement, Developing user defined Exception Classes- The
finally Block.
In this core java training session, you will learn Examples of File IO &
Introduction to JDBC. Topics covered in this session are:
• File IO Continued
• Intro to JDBC (Java Database Connectivity)
For more information about this course visit on this link: https://www.mindsmapped.com/courses/software-development/learn-java-fundamentals-hands-on-training-on-core-java-concepts/
File Handling Presentation As well as File handling code in java Update, Delete, Search, View, Insert in file code are available in this presentation in you face some issues so contact me 03244064060 , Also in my Email: azeemaj101@gmail.com and Twitter @azeemaj101
Exceptions, I/O and Threads Input and Output in Java: The File Class, Standard Streams, Keyboard
Input, File I/O Using Byte Streams, Character Streams, File I/O Using Character Streams -
Buffered Streams, File I/O Using a Buffered Stream, Keyboard Input Using a Buffered Stream,Writing Text Files. Threads: Threads vs. Processes, Creating Threads by Extending Thread,
Creating Threads by Implementing Runnable, Advantages of Using Threads, Daemon Threads,
Thread States, Thread Problems, Synchronization. Exceptions: Exception Handling, The Exception
Hierarchy, throws statement, throw statement, Developing user defined Exception Classes- The
finally Block.
import required package file import java.io.File; The Filed.pdfanandinternational01
// import required package file
import java.io.File;
// The Filedetails class
public class FileDetails {
// Constructor that performs the action
public FileDetails(String filename)
{
// File object to get details
File file=new File(filename);
// printing obsolute path
System.out.println(\"Absolute path of file:\"+file.getAbsolutePath());
// printing file size in bytes
System.out.println(\"File Size in bytes:\"+file.length());
// Checking if file is readable
if(file.canRead())
System.out.println(\"The file is readable\");
else
System.out.println(\"The file is not readable\");
// checking if file is writable
if(file.canWrite())
System.out.println(\"The file is writable\");
else
System.out.println(\"The file is not writable\");
}
// main method goes here
public static void main(String[] args) {
// TODO Auto-generated method stub
// object instantiation
FileDetails fd=new FileDetails(\"anyfile.doc\"); // You should give exact path and file name
here
}
}
// Importing required packages
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
// the writestring class
public class WriteString {
// Writestring class
public WriteString(String filename,String text) throws FileNotFoundException
{
// File object
File file=new File(filename);
// Printsteam class that connects file using file output stream
PrintStream ps=new PrintStream(new FileOutputStream(file));
// using println method to write to the file
ps.println(text);
}
// main method to execute the code
public static void main(String[] args) throws FileNotFoundException
{
// the writestring class instantiation
WriteString ws=new WriteString(\"f1.txt\",\"Hello World\"); // You should give exact path
and file name here
}
}
// importing packages
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
// The writints class
public class WriteInts {
// the constructor to instantiate
public WriteInts(String filename,int[] myArr) throws FileNotFoundException
{
// File object
File file=new File(filename);
// Using print stream to write integers
PrintStream ps=new PrintStream(new FileOutputStream(file));
//Looping through array elements to write every element
for(int i=0;i
Solution
// import required package file
import java.io.File;
// The Filedetails class
public class FileDetails {
// Constructor that performs the action
public FileDetails(String filename)
{
// File object to get details
File file=new File(filename);
// printing obsolute path
System.out.println(\"Absolute path of file:\"+file.getAbsolutePath());
// printing file size in bytes
System.out.println(\"File Size in bytes:\"+file.length());
// Checking if file is readable
if(file.canRead())
System.out.println(\"The file is readable\");
else
System.out.println(\"The file is not readable\");
// checking if file is writable
if(file.canWrite())
System.out.println(\"The file is writable\");
else
System.out.println(\"The file.
Change the code in Writer.java only to get it working. Must contain .pdfsecunderbadtirumalgi
Change the code in Writer.java only to get it working. Must contain methods: logReverse() ,
logMax(), logDuplicates(),
This lab is going to focus on File Output, which you will find is somewhat similar to console
output.
FileMain.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileMain {
public static void main(String[] args) throws IOException{
Scanner scnr = new Scanner(System.in);
System.out.print("Please enter the name of the file you would like to read: ");
String fileName = scnr.next();
Reader reader = new Reader();
ArrayList fileContents = reader.getFileContents(fileName);
System.out.println("Please enter a name for your new file: ");
String newFileName = scnr.next();
Writer fileOut = new Writer(newFileName);
fileOut.logReverse(fileContents);
fileOut.logMax(fileContents);
fileOut.logDuplicates(fileContents);
fileOut.closeWriter();
scnr.close();
}
}
Filetester.java
import java.io.IOException;
import java.util.ArrayList;
public class FileTester {
public static boolean testLogReverse(ArrayList contents) throws IOException {
Writer writer = new Writer("logReverseTest.txt");
writer.logReverse(contents);
writer.closeWriter();
ArrayList expected = new ArrayList();
expected.add("Reversed file contents: ");
expected.add("58");
expected.add("12");
expected.add("19");
expected.add("42");
expected.add("12");
expected.add("End of file.");
Reader testReader = new Reader();
ArrayList result = testReader.getFileContents("logReverseTest.txt");
if(expected.equals(result)) return true;
else return false;
}
public static boolean testLogMax(ArrayList contents) throws IOException {
Writer writer = new Writer("logMaxTest.txt");
writer.logMax(contents);
writer.closeWriter();
ArrayList expected = new ArrayList();
expected.add("The largest number in the file is: 58");
expected.add("End of file.");
Reader testReader = new Reader();
ArrayList result = testReader.getFileContents("logMaxTest.txt");
if(expected.equals(result)) return true;
else return false;
}
public static boolean testLogDuplicates(ArrayList contents) throws IOException {
Writer writer = new Writer("logDuplicatesTest.txt");
writer.logDuplicates(contents);
writer.closeWriter();
ArrayList expected = new ArrayList();
expected.add("Duplicates found: true");
expected.add("End of file.");
Reader testReader = new Reader();
ArrayList result = testReader.getFileContents("logDuplicatesTest.txt");
if(expected.equals(result)) return true;
else return false;
}
public static void main(String[] args) throws IOException {
Reader reader = new Reader();
ArrayList fileContents = reader.getFileContents("nums.txt");
System.out.println("logReverse test passed? " + testLogReverse(fileContents));
System.out.println("logMax test passed? " + testLogMax(fileContents));
System.out.println("logDuplicates test passed? " + testLogDuplicates(fileContents));
}
}
Reader.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Sca.
Know how to redirect input and output- and know how to append to an ex.docxwkelli
Know how to redirect input and output, and know how to append to an existing file. Example: run/usr/local/task with input redirected from blah.txt. and the output appended to file tylk.data
Solution
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
class Main {
public static void main(String[] args) throws IOException {
File dir = new File(\"run/user/local/task.\");
String source = dir.getCanonicalPath() + File.separator + \"blah.txt\";
String dest = dir.getCanonicalPath() + File.separator + \"tylk.data\";
File fin = new File(source);
FileInputStream fis = new FileInputStream(fin);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
FileWriter fstream = new FileWriter(dest, true);
BufferedWriter out = new BufferedWriter(fstream);
String aLine = null;
while ((aLine = in.readLine()) != null) {
out.write(aLine);
out.newLine();
}
// do not forget to close the buffer reader
in.close();
// close buffer writer
out.close();
}
}
.
Explore the innovative world of trenchless pipe repair with our comprehensive guide, "The Benefits and Techniques of Trenchless Pipe Repair." This document delves into the modern methods of repairing underground pipes without the need for extensive excavation, highlighting the numerous advantages and the latest techniques used in the industry.
Learn about the cost savings, reduced environmental impact, and minimal disruption associated with trenchless technology. Discover detailed explanations of popular techniques such as pipe bursting, cured-in-place pipe (CIPP) lining, and directional drilling. Understand how these methods can be applied to various types of infrastructure, from residential plumbing to large-scale municipal systems.
Ideal for homeowners, contractors, engineers, and anyone interested in modern plumbing solutions, this guide provides valuable insights into why trenchless pipe repair is becoming the preferred choice for pipe rehabilitation. Stay informed about the latest advancements and best practices in the field.
Overview of the fundamental roles in Hydropower generation and the components involved in wider Electrical Engineering.
This paper presents the design and construction of hydroelectric dams from the hydrologist’s survey of the valley before construction, all aspects and involved disciplines, fluid dynamics, structural engineering, generation and mains frequency regulation to the very transmission of power through the network in the United Kingdom.
Author: Robbie Edward Sayers
Collaborators and co editors: Charlie Sims and Connor Healey.
(C) 2024 Robbie E. Sayers
import required package file import java.io.File; The Filed.pdfanandinternational01
// import required package file
import java.io.File;
// The Filedetails class
public class FileDetails {
// Constructor that performs the action
public FileDetails(String filename)
{
// File object to get details
File file=new File(filename);
// printing obsolute path
System.out.println(\"Absolute path of file:\"+file.getAbsolutePath());
// printing file size in bytes
System.out.println(\"File Size in bytes:\"+file.length());
// Checking if file is readable
if(file.canRead())
System.out.println(\"The file is readable\");
else
System.out.println(\"The file is not readable\");
// checking if file is writable
if(file.canWrite())
System.out.println(\"The file is writable\");
else
System.out.println(\"The file is not writable\");
}
// main method goes here
public static void main(String[] args) {
// TODO Auto-generated method stub
// object instantiation
FileDetails fd=new FileDetails(\"anyfile.doc\"); // You should give exact path and file name
here
}
}
// Importing required packages
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
// the writestring class
public class WriteString {
// Writestring class
public WriteString(String filename,String text) throws FileNotFoundException
{
// File object
File file=new File(filename);
// Printsteam class that connects file using file output stream
PrintStream ps=new PrintStream(new FileOutputStream(file));
// using println method to write to the file
ps.println(text);
}
// main method to execute the code
public static void main(String[] args) throws FileNotFoundException
{
// the writestring class instantiation
WriteString ws=new WriteString(\"f1.txt\",\"Hello World\"); // You should give exact path
and file name here
}
}
// importing packages
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
// The writints class
public class WriteInts {
// the constructor to instantiate
public WriteInts(String filename,int[] myArr) throws FileNotFoundException
{
// File object
File file=new File(filename);
// Using print stream to write integers
PrintStream ps=new PrintStream(new FileOutputStream(file));
//Looping through array elements to write every element
for(int i=0;i
Solution
// import required package file
import java.io.File;
// The Filedetails class
public class FileDetails {
// Constructor that performs the action
public FileDetails(String filename)
{
// File object to get details
File file=new File(filename);
// printing obsolute path
System.out.println(\"Absolute path of file:\"+file.getAbsolutePath());
// printing file size in bytes
System.out.println(\"File Size in bytes:\"+file.length());
// Checking if file is readable
if(file.canRead())
System.out.println(\"The file is readable\");
else
System.out.println(\"The file is not readable\");
// checking if file is writable
if(file.canWrite())
System.out.println(\"The file is writable\");
else
System.out.println(\"The file.
Change the code in Writer.java only to get it working. Must contain .pdfsecunderbadtirumalgi
Change the code in Writer.java only to get it working. Must contain methods: logReverse() ,
logMax(), logDuplicates(),
This lab is going to focus on File Output, which you will find is somewhat similar to console
output.
FileMain.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileMain {
public static void main(String[] args) throws IOException{
Scanner scnr = new Scanner(System.in);
System.out.print("Please enter the name of the file you would like to read: ");
String fileName = scnr.next();
Reader reader = new Reader();
ArrayList fileContents = reader.getFileContents(fileName);
System.out.println("Please enter a name for your new file: ");
String newFileName = scnr.next();
Writer fileOut = new Writer(newFileName);
fileOut.logReverse(fileContents);
fileOut.logMax(fileContents);
fileOut.logDuplicates(fileContents);
fileOut.closeWriter();
scnr.close();
}
}
Filetester.java
import java.io.IOException;
import java.util.ArrayList;
public class FileTester {
public static boolean testLogReverse(ArrayList contents) throws IOException {
Writer writer = new Writer("logReverseTest.txt");
writer.logReverse(contents);
writer.closeWriter();
ArrayList expected = new ArrayList();
expected.add("Reversed file contents: ");
expected.add("58");
expected.add("12");
expected.add("19");
expected.add("42");
expected.add("12");
expected.add("End of file.");
Reader testReader = new Reader();
ArrayList result = testReader.getFileContents("logReverseTest.txt");
if(expected.equals(result)) return true;
else return false;
}
public static boolean testLogMax(ArrayList contents) throws IOException {
Writer writer = new Writer("logMaxTest.txt");
writer.logMax(contents);
writer.closeWriter();
ArrayList expected = new ArrayList();
expected.add("The largest number in the file is: 58");
expected.add("End of file.");
Reader testReader = new Reader();
ArrayList result = testReader.getFileContents("logMaxTest.txt");
if(expected.equals(result)) return true;
else return false;
}
public static boolean testLogDuplicates(ArrayList contents) throws IOException {
Writer writer = new Writer("logDuplicatesTest.txt");
writer.logDuplicates(contents);
writer.closeWriter();
ArrayList expected = new ArrayList();
expected.add("Duplicates found: true");
expected.add("End of file.");
Reader testReader = new Reader();
ArrayList result = testReader.getFileContents("logDuplicatesTest.txt");
if(expected.equals(result)) return true;
else return false;
}
public static void main(String[] args) throws IOException {
Reader reader = new Reader();
ArrayList fileContents = reader.getFileContents("nums.txt");
System.out.println("logReverse test passed? " + testLogReverse(fileContents));
System.out.println("logMax test passed? " + testLogMax(fileContents));
System.out.println("logDuplicates test passed? " + testLogDuplicates(fileContents));
}
}
Reader.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Sca.
Know how to redirect input and output- and know how to append to an ex.docxwkelli
Know how to redirect input and output, and know how to append to an existing file. Example: run/usr/local/task with input redirected from blah.txt. and the output appended to file tylk.data
Solution
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
class Main {
public static void main(String[] args) throws IOException {
File dir = new File(\"run/user/local/task.\");
String source = dir.getCanonicalPath() + File.separator + \"blah.txt\";
String dest = dir.getCanonicalPath() + File.separator + \"tylk.data\";
File fin = new File(source);
FileInputStream fis = new FileInputStream(fin);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
FileWriter fstream = new FileWriter(dest, true);
BufferedWriter out = new BufferedWriter(fstream);
String aLine = null;
while ((aLine = in.readLine()) != null) {
out.write(aLine);
out.newLine();
}
// do not forget to close the buffer reader
in.close();
// close buffer writer
out.close();
}
}
.
Explore the innovative world of trenchless pipe repair with our comprehensive guide, "The Benefits and Techniques of Trenchless Pipe Repair." This document delves into the modern methods of repairing underground pipes without the need for extensive excavation, highlighting the numerous advantages and the latest techniques used in the industry.
Learn about the cost savings, reduced environmental impact, and minimal disruption associated with trenchless technology. Discover detailed explanations of popular techniques such as pipe bursting, cured-in-place pipe (CIPP) lining, and directional drilling. Understand how these methods can be applied to various types of infrastructure, from residential plumbing to large-scale municipal systems.
Ideal for homeowners, contractors, engineers, and anyone interested in modern plumbing solutions, this guide provides valuable insights into why trenchless pipe repair is becoming the preferred choice for pipe rehabilitation. Stay informed about the latest advancements and best practices in the field.
Overview of the fundamental roles in Hydropower generation and the components involved in wider Electrical Engineering.
This paper presents the design and construction of hydroelectric dams from the hydrologist’s survey of the valley before construction, all aspects and involved disciplines, fluid dynamics, structural engineering, generation and mains frequency regulation to the very transmission of power through the network in the United Kingdom.
Author: Robbie Edward Sayers
Collaborators and co editors: Charlie Sims and Connor Healey.
(C) 2024 Robbie E. Sayers
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
About
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Technical Specifications
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
Key Features
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface
• Compatible with MAFI CCR system
• Copatiable with IDM8000 CCR
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
Application
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Vaccine management system project report documentation..pdfKamal Acharya
The Division of Vaccine and Immunization is facing increasing difficulty monitoring vaccines and other commodities distribution once they have been distributed from the national stores. With the introduction of new vaccines, more challenges have been anticipated with this additions posing serious threat to the already over strained vaccine supply chain system in Kenya.
Student information management system project report ii.pdfKamal Acharya
Our project explains about the student management. This project mainly explains the various actions related to student details. This project shows some ease in adding, editing and deleting the student details. It also provides a less time consuming process for viewing, adding, editing and deleting the marks of the students.
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSEDuvanRamosGarzon1
AIRCRAFT GENERAL
The Single Aisle is the most advanced family aircraft in service today, with fly-by-wire flight controls.
The A318, A319, A320 and A321 are twin-engine subsonic medium range aircraft.
The family offers a choice of engines
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfKamal Acharya
The College Bus Management system is completely developed by Visual Basic .NET Version. The application is connect with most secured database language MS SQL Server. The application is develop by using best combination of front-end and back-end languages. The application is totally design like flat user interface. This flat user interface is more attractive user interface in 2017. The application is gives more important to the system functionality. The application is to manage the student’s details, driver’s details, bus details, bus route details, bus fees details and more. The application has only one unit for admin. The admin can manage the entire application. The admin can login into the application by using username and password of the admin. The application is develop for big and small colleges. It is more user friendly for non-computer person. Even they can easily learn how to manage the application within hours. The application is more secure by the admin. The system will give an effective output for the VB.Net and SQL Server given as input to the system. The compiled java program given as input to the system, after scanning the program will generate different reports. The application generates the report for users. The admin can view and download the report of the data. The application deliver the excel format reports. Because, excel formatted reports is very easy to understand the income and expense of the college bus. This application is mainly develop for windows operating system users. In 2017, 73% of people enterprises are using windows operating system. So the application will easily install for all the windows operating system users. The application-developed size is very low. The application consumes very low space in disk. Therefore, the user can allocate very minimum local disk space for this application.
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdffxintegritypublishin
Advancements in technology unveil a myriad of electrical and electronic breakthroughs geared towards efficiently harnessing limited resources to meet human energy demands. The optimization of hybrid solar PV panels and pumped hydro energy supply systems plays a pivotal role in utilizing natural resources effectively. This initiative not only benefits humanity but also fosters environmental sustainability. The study investigated the design optimization of these hybrid systems, focusing on understanding solar radiation patterns, identifying geographical influences on solar radiation, formulating a mathematical model for system optimization, and determining the optimal configuration of PV panels and pumped hydro storage. Through a comparative analysis approach and eight weeks of data collection, the study addressed key research questions related to solar radiation patterns and optimal system design. The findings highlighted regions with heightened solar radiation levels, showcasing substantial potential for power generation and emphasizing the system's efficiency. Optimizing system design significantly boosted power generation, promoted renewable energy utilization, and enhanced energy storage capacity. The study underscored the benefits of optimizing hybrid solar PV panels and pumped hydro energy supply systems for sustainable energy usage. Optimizing the design of solar PV panels and pumped hydro energy supply systems as examined across diverse climatic conditions in a developing country, not only enhances power generation but also improves the integration of renewable energy sources and boosts energy storage capacities, particularly beneficial for less economically prosperous regions. Additionally, the study provides valuable insights for advancing energy research in economically viable areas. Recommendations included conducting site-specific assessments, utilizing advanced modeling tools, implementing regular maintenance protocols, and enhancing communication among system components.
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.");
}
}
}