File handling

 package com.company;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class CWH_111_FileHandling {
public static void main(String[] args) {
// Code to create a new file
File obj= new File("MyFirstJavaFile.txt");
try {
obj.createNewFile();
} catch (IOException e) {
System.out.println("Unable to create new file: ");
e.printStackTrace();
}

// code to write to a file
try {
FileWriter fileWriter=new FileWriter("MyFirstJavaFile.txt");
fileWriter.write("This is our first file from this java course \n ok now bye ");
fileWriter.close();
} catch (IOException e) {
System.out.println("Unable to write");
e.printStackTrace();
}
// Reading a file
File myFile =new File("MyFirstJavaFile.txt");
try {
Scanner sc= new Scanner(myFile);
while(sc.hasNextLine()){
String line= sc.nextLine();// optional
System.out.println(line);
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
File obj1 =new File("MyFirstJavaFile.txt");
if(obj1.delete()){
System.out.println(obj1.getName() +" File is deleted");
}
else{
System.out.println("Problem occurring in deleting the files");
}
}
}

Comments