Java File Handling

File Handling in Java

Computer understands things in terms of Files, User point of view Drives, Folders, Files and Databases are different things but Computer point of view everything is file only.

Computer point of view - Drive is file, Folder is file, File is file and Database also file.

Using File Class (Pre-defined class) we can handle Computer files.

Examples:

1) Create a Folder

File fileObject = new File("C:/Users/gcreddy/Desktop/gcreddy");   
fileObject.mkdir();

2) Check the existence of gcreddy folder

File fileObject = new File("C:/Users/gcreddy/Desktop/gcreddy");   
boolean a = fileObject.exists();

if ( a == true){
System.out.println("Folder Exists");
}
else{
System.out.println("Folder Not Exists");
}
---------------------------------------------
3) Delete a Folder

File fileObject = new File("C:/Users/gcreddy/Desktop/gcreddy");   
fileObject.delete();
-----------------------------
4) Create a Text File

public static void main(String[] args) throws IOException{
File fileObject = new File("C:/Users/gcreddy/Desktop/Selenium.txt");   
fileObject.createNewFile();
}
-------------------------------------
5) Delete a Text File

public static void main(String[] args) throws IOException{
File fileObject = new File("C:/Users/gcreddy/Desktop/UFT.xlsx");   
fileObject.delete();
}
-----------------------------------------
6) Read a Text File

public static void main(String[] args) throws IOException{
String line;
FileReader file = new FileReader("C:/Users/gcreddy/Desktop/UFT.txt");
BufferedReader br= new BufferedReader(file);

while ((line = br.readLine()) !=null){
System.out.println(line);   
}
br.close();
file.close();
}
------------------------------------------------
7) Write data to a Text file
 

public static void main(String[] args) throws IOException{
FileWriter file = new FileWriter ("C:/Users/gcreddy/Desktop/UFT.txt");
BufferedWriter bw = new BufferedWriter(file);
String data ="Welcome to Java";
bw.write(data);
bw.close();
}
----------------------------------------------------
8) Read a Text File and write to another file.

public static void main(String[] args) throws IOException {
String line;
FileReader file1 = new FileReader("C:/Users/gcreddy/Desktop/UFT.txt");
FileWriter file2 = new FileWriter("C:/Users/gcreddy/Desktop/Selenium.txt");

BufferedReader br = new BufferedReader(file1);
BufferedWriter bw = new BufferedWriter(file2);

while ((line =br.readLine()) != null){
bw.write(line);
bw.newLine();
}
bw.close();
}
}
------------------------------------------------------

0 comments:

Post a Comment