-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileOperations.java
More file actions
63 lines (57 loc) · 2.26 KB
/
Copy pathFileOperations.java
File metadata and controls
63 lines (57 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.io.*;
import java.util.Scanner;
public class FileOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Writing into a file
System.out.println("Enter the file name:");
String fileName = scanner.nextLine();
try {
FileWriter writer = new FileWriter(fileName);
System.out.println("Enter text to write into the file (press Enter to finish):");
String input;
while (!(input = scanner.nextLine()).isEmpty()) {
writer.write(input + "\n");
}
writer.close();
System.out.println("Writing into file successful.");
} catch (IOException e) {
System.out.println("Error writing into file: " + e.getMessage());
}
// Reading from a file
System.out.println("\nReading from file:");
try {
FileReader reader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
System.out.println("Error reading from file: " + e.getMessage());
}
// Rename file
System.out.println("\nEnter new file name:");
String newFileName = scanner.nextLine();
File oldFile = new File(fileName);
File newFile = new File(newFileName);
if (oldFile.renameTo(newFile)) {
System.out.println("File renamed successfully.");
} else {
System.out.println("Error renaming file.");
}
// Delete file
System.out.println("\nDo you want to delete the file? (yes/no)");
String deleteChoice = scanner.nextLine();
if (deleteChoice.equalsIgnoreCase("yes")) {
File fileToDelete = new File(newFileName);
if (fileToDelete.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Error deleting file.");
}
}
scanner.close();
}
}