-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
DiskReader.java
94 lines (74 loc) · 2.59 KB
/
DiskReader.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package me.konloch.kontainer.io;
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
/**
* Used to load from the disk, optional caching
*
* @author Konloch
*/
public class DiskReader {
public static Random random = new Random();
public static HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
/**
* Used to load from file, allows caching
*/
public synchronized static ArrayList<String> loadArrayList(String fileName,
boolean cache) {
ArrayList<String> array = new ArrayList<String>();
if (!map.containsKey(fileName)) {
try {
File file = new File(fileName);
if (!file.exists()) // doesnt exist, return empty
return array;
BufferedReader reader = new BufferedReader(new FileReader(file));
String add;
while ((add = reader.readLine()) != null)
array.add(add);
reader.close();
if (cache)
map.put(fileName, array);
} catch (Exception e) {
e.printStackTrace();
}
} else {
array = map.get(fileName);
}
return array;
}
/**
* Used to load from file
*/
public static String loadAsString(String fileName) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Files.copy(new File(fileName).toPath(), outputStream);
return outputStream.toString("UTF-8");
}
/**
* Used to load a string via line number lineNumber = -1 means random.
*/
public static String loadString(String fileName, int lineNumber,
boolean cache) throws Exception {
ArrayList<String> array;
if (!map.containsKey(fileName)) {
array = new ArrayList<String>();
File file = new File(fileName);
BufferedReader reader = new BufferedReader(new FileReader(file));
String add;
while ((add = reader.readLine()) != null)
array.add(add);
reader.close();
if (cache)
map.put(fileName, array);
} else {
array = map.get(fileName);
}
if (lineNumber == -1) {
int size = array.size();
return array.get(random.nextInt(size));
} else
return array.get(lineNumber);
}
}