-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomFile16.java
More file actions
51 lines (39 loc) · 1.47 KB
/
RandomFile16.java
File metadata and controls
51 lines (39 loc) · 1.47 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
import java.io.*;
public class RandomFile16 {
public static void main(String[] args) throws IOException {
RandomAccessFile numbersFile = new RandomAccessFile("numbers.txt", "rw");
for (int i = 1; i <= 20; i++) {
numbersFile.writeBytes(i + "\n");
}
numbersFile.close();
RandomAccessFile readFile = new RandomAccessFile("numbers.txt", "r");
RandomAccessFile evenFile = new RandomAccessFile("even.txt", "rw");
RandomAccessFile oddFile = new RandomAccessFile("odd.txt", "rw");
String line;
while ((line = readFile.readLine()) != null) {
int num = Integer.parseInt(line.trim());
if (num % 2 == 0) {
evenFile.writeBytes(num + "\n");
} else {
oddFile.writeBytes(num + "\n");
}
}
readFile.close();
evenFile.close();
oddFile.close();
System.out.println("Contents of numbers.txt:");
displayFile("numbers.txt");
System.out.println("\nContents of even.txt:");
displayFile("even.txt");
System.out.println("\nContents of odd.txt:");
displayFile("odd.txt");
}
public static void displayFile(String filename) throws IOException {
RandomAccessFile file = new RandomAccessFile(filename, "r");
String line;
while ((line = file.readLine()) != null) {
System.out.println(line);
}
file.close();
}
}