File operation
File Operation:
Explanation:
- Insert: Adds new data to the end of the file.
- Select: Reads and prints the content of the file.
- Update: Reads the file, replaces occurrences of old text with new text, and writes the updated content back.
- Delete: Deletes the file from the files programs.
Program:
import java.io.File;
import java.io.*;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
class FSC{
public static void main(String args[])throws IOException
{
int i;
DataInputStream d = new DataInputStream(System.in);
String fileName = "msc1.txt";
do
{
System.out.println("\nwhich type of file operation you want to perform?");
System.out.println("\n1.file creation\n2.read\n3.write\n4.update\n5.delete");
System.out.println("Enter your choice:");
i= Integer.parseInt(d.readLine());
switch(i)
{
case 1:
createFile(fileName);
break;
case 2:
readFromFile(fileName);
break;
case 3:
writeToFile(fileName, "Hello!");
break;
case 4:
updateFile(fileName, "\nThis is an appended line.");
break;
case 5:
deleteFile(fileName);
break;
default:
System.out.println("enter choice 1-4");
}
}while(i<=5);
}
public static void createFile(String fileName)
{
File file = new File(fileName);
try
{
if (file.createNewFile())
{
System.out.println("File created: " + file.get");
}
else {
System.out.println("File already exists.");
}
}catch(Exception ex){}
}
public static void writeToFile(String fileName, String content)
{
try
{
FileWriter writer = new FileWriter(fileName);
writer.write(content)
System.out.println("Successfully wrote to the file.");
writer.flush();
writer.close();
}
catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
}
}
public static void updateFile(String fileName, String content)
{
try {
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
System.out.println("Successfully updated the file.");
writer.flush();
writer.close();
}
catch (IOException e) {
System.out.println("An error occurred while updating the file.");
}
}
public static void readFromFile(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
System.out.println("Reading from file:");
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
reader.close();
}
catch (IOException e) {
System.out.println("An error occurred while reading from the file.");
}
}
public static void deleteFile(String fileName)
{
File file = new File(fileName);
if (file.delete())
{
System.out.println("Deleted the file: " + file.getName());
}
else {
System.out.println("Failed to delete the file.");
}
}
}
Comments
Post a Comment