-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFilesMethods.java
More file actions
70 lines (55 loc) · 2.79 KB
/
Copy pathFilesMethods.java
File metadata and controls
70 lines (55 loc) · 2.79 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
64
65
66
67
68
69
package java11.files;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.FileAttribute;
/**
* Java 11 Files Methods Enhancements
* Demonstrates readString() and writeString()
*/
public class FilesMethods {
public static void main(String[] args) {
try {
// Create a temporary file for demonstration
Path tempFile = Files.createTempFile("demo", ".txt");
// 1. writeString() - Write string to file
System.out.println("=== writeString() Examples ===");
String content = "Hello, World!\nThis is a test file.\nJava 11 is great!";
Files.writeString(tempFile, content);
System.out.println("Content written to: " + tempFile);
// Append mode
Files.writeString(tempFile, "\nNew line added", StandardOpenOption.APPEND);
System.out.println("Content appended");
// 2. readString() - Read entire file as string
System.out.println("\n=== readString() Examples ===");
String readContent = Files.readString(tempFile);
System.out.println("Read content:");
System.out.println(readContent);
// With charset
String readWithCharset = Files.readString(tempFile, StandardCharsets.UTF_8);
System.out.println("Read with charset: " + readWithCharset.length() + " characters");
// Comparison with old approach
System.out.println("\n=== Comparison ===");
// Old way (before Java 11)
// String oldWay = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
// Files.write(path, text.getBytes(StandardCharsets.UTF_8));
// New way (Java 11) - much simpler
String newWay = Files.readString(tempFile);
Files.writeString(tempFile, "Updated content");
System.out.println("New way is simpler and more readable");
// Practical example
System.out.println("\n=== Practical Example ===");
Path configFile = Files.createTempFile("config", ".properties");
String configContent = "app.name=MyApplication\napp.version=1.0\napp.debug=true";
Files.writeString(configFile, configContent);
String loadedConfig = Files.readString(configFile);
System.out.println("Loaded config:");
System.out.println(loadedConfig);
// Clean up
Files.deleteIfExists(tempFile);
Files.deleteIfExists(configFile);
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}