-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReadWriteFromFile.java
78 lines (67 loc) · 1.81 KB
/
ReadWriteFromFile.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
package BPlusTree;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class ReadWriteFromFile {
//File parameters
FileReader fileReader;
BufferedReader bufferedReader;
FileWriter fileWriter;
BufferedWriter bufferedWriter;
List<String> input;
public static String line = null;
//receives file name to read from. outputs Array List with list of commands received as input
public List<String> readFile(String fName) {
input = new ArrayList<String>();
try {
fileReader = new FileReader(fName);
bufferedReader = new BufferedReader(fileReader);
//reads one line at a time. Appends input Array List
while((line = bufferedReader.readLine()) != null) {
input.add(line);
}
bufferedReader.close();
fileReader.close();
return input;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
//receives filename and list of output strings as input
public boolean WriteToFile(String fName, List<String> output) {
File outputFile = new File(fName);
try {
//check if file exists already
if(!outputFile.createNewFile()) {
PrintWriter printWriter = new PrintWriter(outputFile);
//rewrite the data in the file so we can start from the beginning
printWriter.print("");
printWriter.close();
}
fileWriter = new FileWriter(outputFile);
bufferedWriter = new BufferedWriter(fileWriter);
for(int i=0; i<output.size(); i++) {
if(output.get(i)!="NL") {
bufferedWriter.write(output.get(i));
}
else {
bufferedWriter.newLine();
}
}
bufferedWriter.close();
fileWriter.close();
return true;
}
catch(Exception e) {
e.printStackTrace();
return false;
}
}
}