Assignment
1. What do you understand by file handling? explain with the help of
program.
File handling in Java implies reading from and writing data to a file. The File class
from the java.io package, allows us to work with different formats of files. In order
to use the File class, you need to create an object of the class and specify the
filename or directory name.
Example:
package FileHandling;
// Import the File class
import java.io.File;
// Import the IOException class to handle errors
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
try {
// Creating an object of a file
File myObj = new File("D:FileHandlingNewFilef1.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
2. Write a program in java to create a file having rollno, name, age, marks in 5
subjects and insert the record in that.
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Assignment6 {
public static void main(String[] args) {
String rollno, name, age, marks;
Scanner sc = new Scanner(System.in);
System.out.printf("\nEnter rollnumber: ");
rollno = sc.nextLine();
System.out.printf("Enter name: ");
name = sc.nextLine();
System.out.printf("Enter age: ");
age = sc.nextLine();
System.out.printf("Enter marks in subject separated by space: ");
marks = sc.nextLine();
sc.close();
try {
FileWriter mywriter = new FileWriter("F:\\Homework BSC
IT\\testfile.txt");
mywriter.write(String.format("Name: %s\nRollNo: %s\nAge: %s\nMarks:
%s\n", name, rollno, age, marks));
mywriter.close();
} catch (IOException e) {
System.out.println(e);
}
}
}