package fileoperations;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class FileOperations {
public static void main(String[] args) throws IOException {
int x;
Scanner scan = new Scanner(System.in);
do {
System.out.println("Select an operation\n1. Open a existing file");
System.out.println("2. Create a new file");
System.out.println("3. Rename a file");
System.out.println("4. Delete a file");
System.out.println("5. Create a directory");
System.out.println("6. Find the absolute path of a file");
System.out.println("7. Get the file names of a directory");
System.out.println("0. To exit");
x = scan.nextInt();
switch(x){
case 1:
File file = new File("data.txt");
try (FileInputStream fis = new FileInputStream(file))
{
System.out.println("File is existing");
}
catch (FileNotFoundException exc)
{
System.out.println("File not found");
}
break;
case 2:
File createFile = new File("Create.txt");
boolean res;
try
{
res = createFile.createNewFile();
if(res){
System.out.println("File created successfully");
}
else{
System.out.println("File already exist");
}
}
catch(IOException E){
System.out.println("Operation not successful");
}
break;
case 3:
File new_file = new File("Create.txt");
File new_name = new File("data.txt");
boolean f = new_file.renameTo(new_name);
if (f == true) {
System.out.println("Renamed successfully");
}
else {
System.out.println("Operation Failed");
}
break;
case 4:
File deleteFile = new File("data.txt");
boolean results = deleteFile.delete();
if(results){
System.out.println("Deleted successfully");
}
else{
System.out.println("Operation Failed");
}
break;
case 5:
File makeDirectory = new File("data.txt");
boolean dir = makeDirectory.mkdir();
if(dir){
System.out.println("Directory created successfully");
}
else{
System.out.println("Directory not created ");
}
break;
case 6:
File ab = new File("data.txt");
String re = ab.getAbsolutePath();
System.out.println(re);
break;
case 7:
String[] name;
File dire = new File("C:\\Users\\computerusername\\Documents");
name = dire.list();
for (String string : name) {
System.out.println(string);
}
}
} while(x != 0);
System.out.println("Exited successfully");
}
}
Comments
Leave a comment