-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileHandlingActivity.java
More file actions
59 lines (55 loc) · 2.3 KB
/
FileHandlingActivity.java
File metadata and controls
59 lines (55 loc) · 2.3 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
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileHandlingActivity {
public static void main(String[] args) throws IOException {
// Your code here
// a. Create main directory
File dirMain = new File("JavaFileSystem");
dirMain.mkdir();
// b. Create three text files
File notes = new File("JavaFileSystem/notes.txt");
notes.createNewFile();
File data = new File("JavaFileSystem/data.txt");
data.createNewFile();
File log = new File("JavaFileSystem/log.txt");
log.createNewFile();
// c. Write messages to files
Files.writeString(Path.of("JavaFileSystem/notes.txt"), "Aiden");
Files.writeString(Path.of("JavaFileSystem/data.txt"), "Yasharian");
Files.writeString(Path.of("JavaFileSystem/log.txt"), "AY");
// d. Read and display file contents
String contents = Files.readString(Path.of("JavaFileSystem/notes.txt"));
String all = contents;
System.out.println(contents);
contents = Files.readString(Path.of("JavaFileSystem/data.txt"));
all = all.concat("\n" + contents);
System.out.println(contents);
contents = Files.readString(Path.of("JavaFileSystem/log.txt"));
all = all.concat("\n" + contents);
System.out.println(contents);
// e. Create backup directory
File dirBackUp = new File("JavaFileSystem/Backup");
dirBackUp.mkdir();
// f. Copy contents to backup file
File backup = new File("JavaFileSystem/Backup/backup.txt");
backup.createNewFile();
Files.writeString(Path.of("JavaFileSystem/Backup/backup.txt"), all);
// g. List all files in both directories
System.out.println("notes.txt\ndata.txt\nlog.txt\nbackup.txt");
debugFileOperation();
}
public static void debugFileOperation() {
try {
// Creating a file with an invalid name (forward slash is invalid for file names on many OS)
File file = new File("fileName.txt");
// Attempting to write to the invalid file
FileWriter writer = new FileWriter(file);
writer.write("Will this fail?");
writer.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
e.printStackTrace();
}
}
}