forked from HarryDulaney/intro-to-java-programming
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExercise17_01.java
47 lines (38 loc) · 1.58 KB
/
Exercise17_01.java
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
package ch_17.exercise17_01;
import java.io.*;
import java.util.Random;
/**
* *17.1 (Create a text file) Write a program to create a file named Exercise17_01.txt if
* it does not exist. Append new data to it if it already exists. Write 100 integers
* created randomly into the file using text I/O. Integers are separated by a space.
*
*/
public class Exercise17_01 {
public static void main(String[] args) {
String[] packageParts = Exercise17_01.class.getPackage().getName().split("\\.");
String filePath = packageParts[0] + File.separator + packageParts[1] + File.separator +
"Exercise17_01.txt";
File file = new File(filePath);
PrintWriter printWriter = null;
try {
if (file.exists()) {
printWriter = new PrintWriter(new FileOutputStream(new File(filePath), false));
} else {
printWriter = new PrintWriter(file);
}
System.out.println("Starting write out random Integer to: " + file.getAbsolutePath());
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 100; i++) {
int num = random.nextInt(100);
sb.append(num).append(" ");
}
printWriter.write(sb.toString());
printWriter.close();
System.out.println("Write out completed successfully.");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("FileNotFoundException occurred.");
}
}
}