-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrite_a_file.java
More file actions
47 lines (42 loc) · 1.81 KB
/
write_a_file.java
File metadata and controls
47 lines (42 loc) · 1.81 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
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class write_a_file {
static void write_file(String filename){
Scanner sc = new Scanner(System.in);
try {
File file = new File("/home/apnx-desk02/fileManipulation/"+filename);
if(file.exists()){
System.out.print("""
File with given name is already exist.
Do you want to override? or
Do you want to update?
""");
String writeOrUpdate = sc.next();
String line;
if("override".equalsIgnoreCase(writeOrUpdate)){
BufferedWriter writer = new BufferedWriter(new FileWriter("/home/apnx-desk02/fileManipulation/"+filename));
System.out.println("Type over to stop writing");
while(!(line = sc.nextLine()).equals("over")){
writer.write(line+"\n");
}
writer.close();
System.out.println("Writing completed");
} else if ("update".equalsIgnoreCase(writeOrUpdate)) {
FileWriter writer = new FileWriter(file, true);
System.out.println("Type over to stop writing");
while(!(line = sc.nextLine()).equals("over")){
writer.write(line+"\n");
}
writer.close();
System.out.println("File updated successfully.");
}
else System.out.println("Invalid input!");
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}