2015-12-03 4 views
-1

Я кодирую GUI экрана входа в систему на Java, что позволяет пользователям входить в систему. Программа ссылается на файл csv, содержащий данные для входа, с которого он собирает данные.Чтение содержимого файла CSV в многомерный массив с использованием Java

Это похоже на другой вопрос, который я видел, how to read csv into multidimensional array in Python

Но в моем случае, его в Java, не Python

Я пытаюсь читать данные из CSV-файла, созданного в Excel в многомерный массив. Я понимаю, как читать его в переменной данных, это делается для каждой строки текстового файла. Но для кода внутри блока catch try, который предназначен для назначения каждого поля каждой строки, элементу массива usersData [] [], просто дает мне ошибки.

Я пробовал все, что знаю, чтобы исправить это, но безуспешно.

public static boolean determineifValid(String userID, String password){ 
    boolean detailsValid = false; 
    // The name of the file 
    String file_Name = "PathologyInterfaceUsers.csv"; 
    File file = new File(file_Name); 
    // The following code block reads the text file in the file_name variable. 
    String usersData[][] = new String[12][3]; 
    // CSV - comma seperated values 
    String data; 
    int firstChar; 
    int field_No; 
    int i; 
    int j; 
    i = 0; 
    try{    
     Scanner inputStream = new Scanner(file); 
     while (inputStream.hasNext()){ 
      data = inputStream.next(); 
      // If the data record contains nothing that indicates the end of the file 
      if(data.equalsIgnoreCase("")){ 
       // Nothing happens and nothing needs to be done 
       System.out.println("End of file reached "); 
      }else{ 

      if(i == 0){ 
      System.out.println("Record No: "+data); 
      }else{ 
       System.out.println(i+"  : "+data); 
      } 
      field_No = 0; 
      firstChar = 0; 
      for(j = 0; j < data.length(); j++){ 
       /* If the current character is a comma separator, then the end of 
       * the data field has been reached. 
       */ 
       if((data.charAt(j)) == ','){ 
        System.out.println("Field "+(field_No + 1)+" is being copied to" 
          + " the data array"); 
        usersData[i][field_No] = data.substring(firstChar, (j-1)); 

        System.out.println("The data for field "+(field_No + 1)+"has been " 
          + "assigned to the "+ (field_No + 1) +" column"); 
        // The index of the 2nd element of usersData, 'field' is incremented by 1 
        field_No = field_No + 1; 
        System.out.println("The field_No has been incremented by 1"); 
        /* The first character of the next field is the one after the 
        * comma (value divider) 
        */ 
        firstChar = j + 1; 
        System.out.println("Value divider ','"); 
       }else if(j == data.length()){ 
        usersData[i][field_No] = data.substring(firstChar, j); 
       } 
      } 
      i = i + 1; 
      } 

     } 
     inputStream.close(); 
    }catch (FileNotFoundException e){ 
     System.out.println("We are so sorry, but an error has occured! "); 
    } 
+0

Какая ошибка дает и что такое трассировка стека? – StackFlowed

+1

Без ошибки мы не можем вам помочь, кстати, я попытаюсь прочитать каждую отдельную строку, а затем разделить ее на [метод разделения класса String] (https://docs.oracle.com/javase/ 6/docs/api/java/lang/String.html # split (java.lang.String)) и сэкономит вам много времени –

+0

Эй, ребята. Извините, я не опубликовал сообщение об ошибке. Но мне больше не понадобится, потому что я нашел более эффективный способ чтения csv. файл в другом месте в переполнении стека. Я отправлю его всем, кто может понадобиться. –

ответ

-1

Csv может быть сложнее обрабатывать правильно, чем кажется. Просто используйте библиотеку, предназначенную для этого, такую ​​как uniVocity-parsers и сохраните головную боль. Вот простой пример:

CsvParserSettings settings = new CsvParserSettings(); //many options here, check the tutorial. 
CsvParser parser = new CsvParser(settings); 
List<String[]> allRows = parser.parseAll(new FileReader(file)); 

Раскрытие информации: Я являюсь автором этой библиотеки. Это бесплатно и бесплатно (лицензия Apache V2.0).

Смежные вопросы