Q.Write a java program for the following: [25 M]
- delete a file..
- To display path of a file
- To create a file.
- To rename a file.
import java.io.*;
import java.util.Scanner;
class FileOperations
{
public static void main(String args[]) throws IOException
{
Scanner sc = new Scanner(System.in);
// 1. Create File
File f1 = new File("sample.txt");
if(f1.createNewFile())
System.out.println("File created successfully.");
else
System.out.println("File already exists.");
// 2. Rename File
File f2 = new File("renamed.txt");
if(f1.renameTo(f2))
System.out.println("File renamed successfully.");
else
System.out.println("Rename failed.");
// 3. Display Path
System.out.println("File path: " + f2.getAbsolutePath());
// 4. Delete File
System.out.print("Do you want to delete file? (yes/no): ");
String ch = sc.next();
if(ch.equalsIgnoreCase("yes"))
{
if(f2.delete())
System.out.println("File deleted successfully.");
else
System.out.println("Delete failed.");
}
}
}