2012-10-05 49 views
-1

开始一个项目,这irriating我。我认为代码是好的,但我不明白如何返回记录或解析该行。导入CSV文件和比较用户输入

我有一个CSV文件,该文件显示这样的天秤座。

USER PASSWORD 克里斯密码 米歇尔密码 约翰密码

我收到用户输入自己的用户名和密码,然后试图比较这些反对CSV以确保1)用户名存在, 2)如果有,密码是正确的。说实话,因为它不是规范的一部分,但我想这样做,我怀疑这将是同样的问题,因为我也不得不哪些部分2不是必需的。正如我所说的,我觉得代码是好的,但我不知道是什么格式的变量thisLine会和我的else语句中的BufferedReader正确移动到下一行?

我可以使用thisLine.trim()削减USER PASSWORD不只是用户?

static void readFromCsvFile(String sFileName,User user)throws FileNotFoundException String thisLine;

 try 
     { 
      BufferedReader reader = new BufferedReader(new FileReader(sFileName)); 
      thisLine = reader.readLine(); 
      System.out.print(thisLine); 

      while((thisLine = reader.readLine()) != null) 
       { 
        if (user.displayUserName() == thisLine) 
        { 
        System.out.print("\nUser <-" + user.displayUserName() + " -> exists!"); 
        reader.close(); 
        } 

        else 
        { 
         thisLine = reader.readLine(); 
        } 
       } 

     } 
     catch(IOException e) 
     { 
      System.out.print("\nUser does not exist\n"); 
      e.printStackTrace(); 
     } 

回答

2

几点看法,在这里:

1)thisLine.trim()将只是删除尾随空白的开头和的thisLine内容结束。这是正常的话,特别是如果你要比较两个字符串,但它不会分裂从变量的用户名和密码。

2)要拆分这两个不同的值,你应该使用thisLine.split(" ")(我假设你的CSV文件使用空格来分隔不同的字段)。

3)另一个错误是比较字符串使用==而不是equals,这是正确的方法。

4)由于您在while条件读取一个新行不需要内部reader.readLine()

5)最后,不要关闭内循环流(或阅读器)!!在try/catch/finally块上执行。

所以,用这些更正您的代码如下:

static void readFromCsvFile(String sFileName, User user) throws FileNotFoundException { 
    String thisLine; 
    BufferedReader reader = new BufferedReader(new FileReader(sFileName)); 
    try 
    { 

     thisLine = reader.readLine(); 
     System.out.print(thisLine); 

     while((thisLine = reader.readLine()) != null)    
      { 
       thisLine = thisLine.trim(); 
       String username = thisLine.split(" ")[0]; 
       if (user.displayUserName().equals(username)) 
       { 
       System.out.print("\nUser <-" + user.displayUserName() + " -> exists!"); 
       break; // break the loop 
       }      
      } 

    } 
    catch(IOException e) 
    { 
     System.out.print("\nUser does not exist\n"); 
     e.printStackTrace(); 
    } 
    finally { 
     try { 
      reader.close(); 
     } catch (IOException e) { /* ignore */ } 
    } 
} 
+0

干杯。试过但同样的问题!它终止于CSV文件的第一行,并且不会继续。第一行永远不会是正确的,因为它只是标题。 –

+0

修正了它。我正在使用\ t分隔记录,而不是, –

1

若要比较两个字符串:

firstString.equal(secondString); 

的另一个问题是thisLine包含用户名和密码(“克里斯密码”为例),所以你必须分割你的线来分隔的用户名(“克里斯”)和密码(“密码”)。

while((thisLine = reader.readLine()) != null) 
{ 
    thisLine = thisLine.trim() 
    // userData[0] => Username and userData[1] => Password 
    String userData[] = thisLine.split(" "); 
    if (user.displayUserName().equal(userData[0])) 
    { 
     System.out.print("\nUser <-" + user.displayUserName() + " -> exists!"); 
    } 
}