这是修改后的代码,当我运行程序时它可以工作,但它没有按我预期的那样工作。我不知道为什么它不会写出我在输入“add”后输入的行,而且当我输入“show”时它也没有显示任何内容。好像我可能会遗漏一些东西:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.List;
public class unfinished {
public static void main(String[] args) throws IOException {
//String command;
//int index = 0;
Path path = FileSystems.getDefault().getPath("source.txt");
List<String> list = loadList(path);
try(Scanner sc = new Scanner(System.in)){
// System.out.print("Enter the Command: ");
String[] input = sc.nextLine().split(" ");
while(input.length > 0 && !input[0].equals("exit")){
switch(input[0]){
case "add" : addToList(input, list); break;
case "remove" : removeFromList(input, list); break;
case "show": showList(input, list); break;
}
}
input = sc.nextLine().split(" ");
}
saveList(path, list);
}
这是我用于排序和清除的旧代码的一部分:
/**
Collections.sort(MenuArray);
int i = 0;
for (String temporary : MenuArray) {
System.out.println(++i + ". " + temporary);
}
//clear
MenuArray.clear();
System.out.println("All objects have been cleared !");
*/
private static void saveList(Path path, List<String> list) throws IOException {
// TODO Auto-generated method stub
Files.write(path, list, Charset.defaultCharset(),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING);
}
private static void removeFromList(String[] input, List<String> list) {
// TODO Auto-generated method stub
}
private static void showList(String[] input, List<String> list) {
// TODO Auto-generated method stub
}
private static void addToList(String[] input, List<String> list) {
// TODO Auto-generated method stub
}
private static List<String> loadList(Path path) throws IOException {
// TODO Auto-generated method stub
return Files.readAllLines(path, Charset.defaultCharset());
}
}