java - 如何在java中使用csv文件调用方法?

标签 java file loops csv

我正在开发一个地址簿程序,我想做的最后一件事是允许用户指定一个充满命令的文件,例如:添加“名称”、删除“名称”、打印、等等。

所有这些方法都已在我的程序中实现,并且当我在控制台中键入命令时它们会起作用。

我尝试使用 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

}

enter image description here

最佳答案

您只需将包含所有文件内容的一个字符串添加到数组中。 我不确定你的 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/

相关文章:

java - netbeans 调试最佳实践

java - Spring JpaRepository : delete() with subsequent save() in the same transaction

java - 如何在java中将字符串转换为语言环境

c - 我正在尝试将守护程序的输出记录到文件中

arrays - 在 PL/pgSQL 中循环遍历给定的值列表

java - UltraEdit Java 编辑器设置

swift - 如何在同一项目中使用其他 swift 文件(同一目标)的函数

c - 读取一个文本文件的确定部分,忽略注释 - C 语言

javascript - JPG转div JS+循环

php - SQL Select 上的循环