Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
Now Reading
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Java, one of the most popular programming languages, supplies extensive support to numerous functional operations like file handling, database, sockets, etc. File handling in Java is a crucial function that allows you to conduct different tasks on a stored file, such as writing, reading, etc.
This tutorial presents a thorough synopsis of file handling and its functionality in Java.
You can work with files in Java by using the File Class inside the java.io package. Generating an object of the class and then adding a specified name to the file allows you to use the File Class. File handling in Java primarily stands for reading from, followed by writing data to a particular file.
The File Class lets you perform various operations on different file formats once an object of the class with a specific filename or directory name is created. File handling presents you with several benefits, such as:
Java uses the concept of streams to conduct I/O operations on its files. Hence, the streams play an important role in the file-handling operations of Java.
In Java, a stream is a sequence of data used to perform I/O operations on files. Based on the functional aspects, streams can be categorized into two types, namely:
The stream API is used for processing groups of data. JavaScript can programmatically access the streams of data received over the network using stream API. It also allows Java to process the data streams as per the developer's requirements.
Stream API can also be divided into two categories depending on the data type, which are:
Let us write a program that copies the contents of a file named "source.txt" to another file named "destination.txt".
We will first create the source.txt file and put the text ‘upGrad teaches programming.’ in this file. It is also important to note that we must create the java (upGradTutorials.java) file in the same directory as the source.txt file.
Then, we will run the program below:
import java.io.*;
public class CopyFileExample {
public static void main(String[] args) {
try {
File sourceFile = new File("source.txt");
File destinationFile = new File("destination.txt");
FileReader fileReader = new FileReader(sourceFile);
FileWriter fileWriter = new FileWriter(destinationFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Once we run the program, a new file destination.txt will get created in the directory with the same text.
The code begins by creating two File objects: sourceFile represents the source file ("source.txt"), and destinationFile represents the destination file ("destination.txt"). A FileReader and FileWriter are created to read from the source file and write to the destination file. BufferedReader and BufferedWriter are used for efficient reading and writing.
Inside the while loop, each source file line is read using readLine() and written to the destination file using write(). The newLine() method is used to insert line breaks. The loop continues until there are no more lines to read from the source file. Finally, the BufferedReader and BufferedWriter are closed to flush the buffers and release system resources.
Now, let us write a program that reads the contents of a file named "upGrad.txt" and prints each line to the console.
We will first create the upGrad.txt file and put the text ‘upGrad teaches Java programming.’ inside this file. Then, we will create the java (upGradTutorials.java) file in the same directory as the txt file.
Once we run the program, it will read the contents of the upGrad.txt file and print each line to the console.
import java.io.*;
public class upGradTutorials {
public static void main(String[] args) {
try {
File file = new File("upGrad.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This program begins by creating a File object representing the file "upGrad.txt". Then, a FileReader is created to read the contents of the file, and a BufferedReader is used to read the text efficiently. Within a while loop, each line of the file is read and stored in the variable line.
The loop continues until there are no more lines to read (i.e., readLine() returns null). For each line, the program prints it to the console. Finally, the BufferedReader is closed to release system resources and handle any potential exceptions.
We have learned how to read files in Java, let us now learn how to write a program that will first create a ‘upGrad.txt’ file and then write the two strings of text ‘upGrad teaches programming.’ and ‘upGrad teaches Java.’ in that txt file.
Contents of the created txt file:
import java.io.*;
public class upGradTutorials {
public static void main(String[] args) {
try {
File file = new File("upGrad.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("Hello, World!");
bufferedWriter.newLine();
bufferedWriter.write("This is a sample text.");
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This program begins by creating a File object representing the file "upGrad.txt". Next, a FileWriter is created to write the file's contents, and a BufferedWriter is used to write the text efficiently.
The program then uses the write() method of the BufferedWriter to write the string "upGrad teaches programming." to the file. The newLine() method moves the cursor to the next line. Another string, "upGrad teaches Java." is written to the file. Finally, the BufferedWriter is closed to flush the buffer and release system resources.
Here are some commonly used methods in the File class for file handling:
This code creates a new file named "upGrad.txt" using the createNewFile() method. If the file is successfully created, it prints a message indicating so. If the file already exists, it prints a message stating it already exists.
import java.io.File;
import java.io.IOException;
public class upGradTutorials {
public static void main(String[] args) {
try {
File file = new File("upGrad.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This code deletes a file named "upGrad.txt" using the delete() method. If the file is successfully deleted, it prints a message indicating so. If the deletion fails, it prints a message stating that the file couldn't be deleted.
import java.io.File;
public class upGradTutorials {
public static void main(String[] args) {
File file = new File("upGrad.txt");
if (file.delete()) {
System.out.println("File deleted: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
This code renames a file named "example.txt" to "upGrad.txt" using the renameTo() method. If the renaming is successful, it prints a message indicating so. If the renaming fails, it prints a message stating that the file couldn't be renamed.
import java.io.File;
public class upGradTutorials {
public static void main(String[] args) {
File oldFile = new File("example.txt");
File newFile = new File("upGrad.txt");
if (oldFile.renameTo(newFile)) {
System.out.println("File renamed successfully.");
} else {
System.out.println("Failed to rename the file.");
}
}
}
This code checks the attributes of a file named "upGrad.txt" using the File class. It first checks if the file exists using the exists() method. If the file exists, it prints the file name, absolute path, size, last modified timestamp, and whether it is a directory or a regular file. If the file doesn't exist, it prints a message indicating it doesn't exist.
import java.io.File;
public class upGradTutorials {
public static void main(String[] args) {
File file = new File("upGrad.txt");
if (file.exists()) {
System.out.println("File name: " + file.getName());
System.out.println("File path: " + file.getAbsolutePath());
System.out.println("File size: " + file.length() + " bytes");
System.out.println("Last modified: " + file.lastModified());
System.out.println("Is directory? " + file.isDirectory());
System.out.println("Is file? " + file.isFile());
} else {
System.out.println("File does not exist.");
}
}
}
You can perform several operations on a file in Java. The four major operations include creating a file, getting file information, writing to a file, and reading from a file. These activities can be easily accomplished using the different techniques of file handling in Java.
A comprehensive course can help you if you want to gain deeper insight into file handling and other operations in Java. upGrad offers curated courses on Java that can increase your expertise on the subject. Enrolling in these courses allows you to gain more knowledge about the core Java concepts.
1. What are file handling methods?
File handling is the process of storing the available data or information in a file with the assistance of a program. In Java, you can store the entire available data of a program inside a file with the help of file handling. The data can be retracted or fetched back from the files whenever you need them, whereas using file handling in Java allows you to operate the stored files in another program.
2. How to perform file handling in Java?
You can get all the classes required for performing every input and output operation in Java from the java.io package. The Java I/O API allows you to work with file handling in Java.
3. Why is a string immutable in Java?
Strings that contain the same values try to minimize unwanted copies of the content, which makes them share the storage of a single pool. Once a string is created, its internal content cannot be further changed since adding any changes to its values leads to creating a new string. This explains why strings in Java are immutable or unchangeable.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...