我正在开发一个地址簿程序,我想做的最后一件事是允许用户指定一个充满命令的文件,例如:添加“名称”、删除“名称”、打印、等等。
所有这些方法都已在我的程序中实现,并且当我在控制台中键入命令时它们会起作用。
我尝试使用 for 循环从文件输入流中读取命令,但它只处理 csv 文件内的第一个命令。我什至尝试先将列出的命令添加到字符串数组中,然后从流数组中读取,我得到了相同的结果。
这是我当前的代码,它将处理第一个命令,但不会处理其他命令。
private static void fileCommand(String file) throws IOException {
File commandFile = new File(file);
try {
FileInputStream fis = new FileInputStream(commandFile);
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
StringBuilder builder = new StringBuilder();
int ch;
while((ch = fis.read()) != -1){
builder.append((char)ch);
}
ArrayList<String> commands = new ArrayList<String>();
commands.add(builder.toString());
for(int i = 0; i<commands.size();i++){
if (commands.get(i).toUpperCase().startsWith("ADD")|| commands.get(i).toUpperCase().startsWith("DD")){
addBook(commands.get(i));
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
}
最佳答案
您只需将包含所有文件内容的一个字符串添加到数组中。 我不确定你的 csv 文件到底是什么样子,但试试这个:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class SOQuestion {
private static void fileCommand(String file) throws IOException {
Path pathFile = Paths.get(file);
List<String> allLines = Files.readAllLines(pathFile, StandardCharsets.UTF_8);
for (String line : allLines) {
if (line.toUpperCase().startsWith("ADD")) {
addBook(line);
}
}
}
private static void addBook(String line) {
//Do your thing here
System.out.println("command: "+line);
}
public static void main(String[] args) throws IOException {
fileCommand("e:/test.csv"); //just for my testing, change to your stuff
}
}
假设您的 csv 文件每一行都有一个命令,实际命令是每一行的第一部分。
关于java - 如何在java中使用csv文件调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33070162/