Repository navigation
Expand file tree
/
Copy pathSave.java
More file actions
67 lines (59 loc) · 2.02 KB
/
Copy pathSave.java
File metadata and controls
67 lines (59 loc) · 2.02 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
package commands;
import java.io.*;
import java.util.List;
import constants.Exceptions;
import driver.IShellState;
/**
* This class is responsible for saving the current JShell session into a file
*/
public class Save extends Command {
public Save() {
super(1, 1);
}
/**
* This method will save the current JShell session into a file which will
* created/ overwritten at the given path
* @param shellState is the current state of JShell program
* @param arguments list of arguments that were passed along with command
* @throws Exception if any of the paths is invalid
*/
public String executeCommand(IShellState shellState, List<String> arguments)
throws Exception {
try {
checkArgumentsNum(arguments);
String path = arguments.get(0);
if (!path.contains("/")) {
throw new Exception(Exceptions.WRONG_PATH_INPUT_MSG);
}
saveToFile2(shellState, path);
return "";
} catch (IOException e) {
throw new Exception(Exceptions.WRONG_PATH_INPUT_MSG);
}
}
private void saveToFile2(IShellState shellState, String path) throws IOException {
FileOutputStream fileOut =
new FileOutputStream(path);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(shellState);
out.close();
fileOut.close();
}
private void saveToFile1(IShellState shellState, String path) throws IOException {
FileWriter fileWriter = new FileWriter(path);
BufferedWriter bw = new BufferedWriter(fileWriter);
//add history
for (String commandLine : shellState.getHistory()) {
bw.write(commandLine);
bw.newLine();
}
bw.write("*****");
bw.newLine();
// add content to file
for (String commandLine : shellState.getCorrectHistory()) {
bw.write(commandLine);
bw.newLine();
}
bw.close();
}
}