-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
53 lines (50 loc) · 1.63 KB
/
Main.java
File metadata and controls
53 lines (50 loc) · 1.63 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
import java.io.*;
public class Main {
public static void main(String[] args) {
// Create a file and write to it
try {
// Connect to the file; create it if necessary
FileWriter fw = new FileWriter("example.txt");
// Attach a buffer to the file
BufferedWriter bw = new BufferedWriter(fw);
// Use the buffer to write to the file
bw.write("Write this to file example.txt.");
bw.newLine();
bw.write("And also this.");
bw.newLine();
bw.write("And this.");
// Close the buffer and the file writer to
// make sure the file is saved properly
bw.close();
fw.close();
} catch (Exception ex) {
// If an error occurs, this code will run
System.out.println(ex.getMessage());
}
// Open the created file and read from it
try {
// Connect to the file
FileReader fr = new FileReader("example.txt");
// Attach a buffer to the file
BufferedReader br = new BufferedReader(fr);
// Read a line of data from the file
String line = br.readLine();
// Loop until no more lines are in the file
while (line != null) {
// Print out the line you read in (just to
// show that it's working)
System.out.println(line);
// Get the next line
line = br.readLine();
}
// Close the buffer and file; if you don't do
// this, they will be "locked" and other code
// won't be able to use the file correctly
br.close();
fr.close();
} catch (Exception ex) {
// If an error occurs, this code will run
System.out.println(ex.getMessage());
}
}
}