-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFileUtils.java
More file actions
69 lines (59 loc) · 1.91 KB
/
FileUtils.java
File metadata and controls
69 lines (59 loc) · 1.91 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
import java.io.*;
public class FileUtils {
public static String readFile(File fileName) throws IOException {
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(fileName));
while (br.ready()) {
str.append((char) br.read());
}
br.close();
return str.toString();
}
/*
* tries to write text to File fileName, if file doesn't exist, then creates
* file with name fileName
*/
public static boolean writeFile(String fileName, String text) {
try {
PrintWriter pr = new PrintWriter(fileName);
pr.write(text);
pr.close();
} catch (Exception fileNotFoundException) {
File fl = new File(fileName);
PrintWriter pr;
try {
pr = new PrintWriter(fl);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
pr.write(text);
pr.close();
}
return true;
}
public static int countCharacters(String fileName) throws IOException {
int characterCount = 0;
BufferedReader br = new BufferedReader(new FileReader(fileName));
while (br.ready()) {
br.read();
characterCount++;
}
br.close();
return characterCount;
}
public static void main(String[] args) throws IOException {
String text = "123456789";
String fileName = "NamedFile.txt";
// test writeFile
writeFile(fileName, text);
// test readFile
File testFile = new File(
"NamedFile.txt");
System.out.println(readFile(testFile));
// test countCharacters
System.out.println(countCharacters(fileName));
// make sure we finished the tester
System.out.println("end tester");
}
}