-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMyFileWriter.java
More file actions
56 lines (46 loc) · 1.82 KB
/
MyFileWriter.java
File metadata and controls
56 lines (46 loc) · 1.82 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
import java.io.*;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
public class MyFileWriter {
public static void main(String[] args) {
String data = "Hello, World!";
String fileName2 = "example2.txt";
printFileSize(".gitignore");
// 2. Using BufferedWriter
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileName2))) {
bufferedWriter.write(data);
} catch (IOException e) {
e.printStackTrace();
}
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(".notAPassword.txt"))) {
bufferedWriter.write("password");
} catch (IOException e) {
e.printStackTrace();
}
File file = new File(".topSecret");
file.mkdirs();
Path filePath = Paths.get(".topSecret", "classified");
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath.toFile()))) {
bufferedWriter.write("too bad not telling you any secrets");
} catch (IOException e) {
e.printStackTrace();
}
printTotalFileSize("example2.txt", ".notAPassword.txt", ".topSecret/classified");
}
// Calculate and print the file size using the File class
private static void printFileSize(String fileName) {
File f = new File (fileName);
long fSize = f.length();
System.out.println("file size: " + fSize);
}
private static void printTotalFileSize(String... fileNames) {
long totalSize = 0;
for (String fileName : fileNames) {
File file = new File(fileName);
if (file.exists()) {
totalSize += file.length();
}
}
System.out.println("Total size of all files: " + totalSize + " bytes");
}
}