2015-10-11 47 views
0

我正在研究地址簿程序,而我正在尝试做的最后一件事是允许用户指定一个充满命令的文件,例如:添加名称,删除名称,打印和等等。如何在java中使用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

回答

1

您正在使用该文件的所有内容复制到阵列中添加只有一个字符串。 我不知道你的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文件有每行一个命令和实际的命令是每行的第一部分。

+0

我将上传我的csv文件的屏幕截图。我试过你的源代码,它仍然做同样的事情。它只添加第一行。 – Remixt

+0

我自己尝试过,当然在发布之前,它正在工作,你的csv文件看起来就像我所想的那样。我不认为你实际上在使用我的源代码。 –

+0

我直接从堆栈溢出复制并粘贴它。 – Remixt

相关问题