2013-08-23 3 views
-3

Ниже приведена часть программы, которую я написал для итерации через файл, чтобы найти и сравнить два отдельных числа.NullPointerException при чтении txt-файла

Он ищет каждую строку для начальной точки, где линия равна «[Устройство | Датчики | Контрольная сумма]». Затем он ищет первое и второе вхождения «Значение», получает значение Hex на этой строке, преобразует его в тип long. Если эти два длинное число равно мы хорошо, в противном случае мы сообщить о проблеме

Вот выдержка из файла я использую

Address(18) = 0x0053 
Page(18) = Sensor 
Value(19) = 0x1 
Desc(19) = used bytes from high priority task 
Address(19) = 0x0053 
Byte_No(19) = 2 
Page(19) = Sensor 
;end of section [Device|Sensors|Stack] 
[Device|Sensors|Checksum] 
Address(18) = 0x0053 
Page(18) = Sensor 
Value(2) = 0xE0A64F36 
Address(18) = 0x0053 
Page(18) = Sensor 
Default(19) = 0x00 
Value(3) = 0xE0A64F36 
Page(18) = Sensor 
Desc(19) = used bytes from high priority task 
;end of section [Device|Sensors|Checksum] 

Я не могу найти то, что именно не так с этим кодом несмотря на попытки отладить его уже. Петли, которые я использовал, кажутся звуковыми.

try { 

do {//read line then check if line is "[Device|Sensors|Checksum]" WHILE line isn't ";end of section [Device|Sensors|Checksum]"      

    line = reader.readLine();//Reads all lines up to "[Device|Sensors|Checksum]" 

    if (line.equals("[Device|Sensors|Checksum]")) { //IF line is "[Device|Sensors|Checksum]" then 
                //(check if line is "Value") ELSE read next line      
    do {// DO read line and (check if line is "Value") WHILE line doesn't contain "Value" 

    line = reader.readLine();//Reads all line up to first "Value" 

    if (line.contains("Value")) { // IF line is "Value" then retrieve necessary value 
            // ELSE read next line 

     Hex1 = line.split("=")[1].trim(); 
     l1 = Long.parseLong(Hex1.substring(2), 16); 
     JFrame frame1 = new JFrame("JOptionPane showMessageDialog example"); 
     JOptionPane.showMessageDialog(frame1, "Value has hex number\n " + Hex1 + "\n\n and integer\n" + l1 + "\n"); 

     System.out.println("Here's the line read " + line); 
     System.out.println("Here's the hex number from the line " + Hex1); 
     System.out.println("Here's the integer from the hex number " + l1 + "\n"); 

     break; 
    } 
    } while (!"Value".contains(line = reader.readLine()));//while2 


    line = reader.readLine(); //Reads the line AFTER the first "Value" has been found 

    do {// Read line and check if line has "Value" WHILE line doesn't contain "Value" 

    line = reader.readLine();//Reads all lines up to second "Value" 

    if (line.contains("Value")) { // IF line is "Value" then retrieve necessary value 
            // ELSE read next line 

     Hex2 = line.split("=")[1].trim(); 
     l2 = Long.parseLong(Hex2.substring(2), 16); 
     JFrame frame2 = new JFrame("JOptionPane showMessageDialog example"); 
     JOptionPane.showMessageDialog(frame2, "Value has hex number\n " + Hex2 + "\n\n and integer\n" + l2 + "\n"); 

     System.out.println("Here's the line read " + line); 
     System.out.println("Here's the hex number from the line " + Hex2); 
     System.out.println("Here's the integer from the hex number " + l2 + "\n"); 

     break; 

    } 
    } while (!"Value".contains(line = reader.readLine())); 
    } 
    } while (!";end of section [Device|Sensors|Checksum]".equals(line = reader.readLine())); 
if (l1 == l2) { 
    JOptionPane.showMessageDialog(null, "Both checksum values ARE equal!"); 
    int status1 = 0; 
    System.exit(status1); 
} else { 
    JOptionPane.showMessageDialog(null, "Both checksum values NOT equal"); 
    int status2 = 0; 
    System.exit(status2); 
    } 

} catch (IOException e) { 
    System.out.println("IO Exception. Could not read file!"); 
} 

EDIT

Выходной и Трассировка стека для NPE является

run: 
Here's the line read Value(2) = 0xE0A64F36 
Here's the hex number from the line 0xE0A64F36 
Here's the integer from the hex number 3768995638 

Exception in thread "main" java.lang.NullPointerException 
at robertskostalproject.checksumFinder.HexFinder(checksumFinder.java:32) 
at robertskostalproject.checksumGUI.askDirectory(checksumGUI.java:43) 
at robertskostalproject.RobertsKostalProject.main(RobertsKostalProject.java:18) 
BUILD STOPPED (total time: 11 seconds) 
+0

ли вы на самом деле * * значит пропустить строку непосредственно после '[Device | Sensosrs | Контрольная сумма]'? Кроме того, это не помогает в том, что ваш код сильно отступил, вы не сказали нам, где вы получили исключение, или как выглядит файл, или что происходит, когда вы не отлаживаете. Пожалуйста, прочитайте http://tinyurl.com/so-list –

+0

Пожалуйста, не ругайтесь на SO (даже не совсем мягкая ругань, используемая в вашем названии). –

+0

И «Значение» .contains (variable) '? – chrylis

ответ

0

Вот что у меня есть сейчас. К счастью, много изменений, и это работает!

class checksumFinder { 

public static long l1 = 1; 
public static long l2 = 0; 
//Default to not equal 

String HexFinder(JFileChooser inFileName, String line, String Hex1, String Hex2) 
throws FileNotFoundException, IOException { 

    File file = inFileName.getSelectedFile(); 
    BufferedReader reader = new BufferedReader(new FileReader(file)); 

    try { 

     line = reader.readLine();//Read all lines up to "[Device|Sensors|Checksum]" 

     do {//Read line then check if line is "[Device|Sensors|Checksum]" WHILE isn't ";end of section [Device|Sensors|Checksum]"      

     line = reader.readLine(); 

     if (line.equals("[Device|Sensors|Checksum]")) { //IF line is "[Device|Sensors|Checksum]" then 
                 //(check if line is "Value") ELSE read next line      
      do {// DO read line and check line is "Value" WHILE line doesn't contain "Value" 

      if (line.contains("Value")) { //IF line is "Value" then retrieve necessary value 
              // ELSE read next line 

       Hex1 = line.split("=")[1].trim(); 
       l1 = Long.parseLong(Hex1.substring(2), 16); 
       JFrame frame1 = new JFrame("JOptionPane showMessageDialog example"); 
       JOptionPane.showMessageDialog(frame1, "Value has hex number\n " + Hex1 + "\n\n and integer\n" + l1 + "\n"); 

       System.out.println("Here's the line read " + line); 
       System.out.println("Here's the hex number from the line " + Hex1); 
       System.out.println("Here's the integer from the hex number " + l1 + "\n"); 

       break; 
      } 
      } while (!"Value".contains(line = reader.readLine()));//while2 

      line = reader.readLine(); //Read the line AFTER first "Value" has been found 

      do {//Read line and check if line has "Value" WHILE line doesn't contain "Value" 

      if (line.contains("Value")) { // IF line is "Value" then retrieve necessary value 
             // ELSE read next line 

      Hex2 = line.split("=")[1].trim(); 
      l2 = Long.parseLong(Hex2.substring(2), 16); 
      JFrame frame2 = new JFrame("JOptionPane showMessageDialog example"); 
      JOptionPane.showMessageDialog(frame2, "Value has hex number\n " + Hex2 + "\n\n and integer\n" + l2 + "\n"); 

      System.out.println("Here's the line read " + line); 
      System.out.println("Here's the hex number from the line " + Hex2); 
      System.out.println("Here's the integer from the hex number " + l2 + "\n"); 

      break; 
      } 
     } while (!"Value".contains(line = reader.readLine()));//while3 

     while (!";end of section [Device|Sensors|Checksum]".equals(line)){ 
      line = reader.readLine(); 
     } 
     } 
    } while (!";end of section [Device|Sensors|Checksum]".equals(line)); //while1 

    if (l1 == l2) { 
     JOptionPane.showMessageDialog(null, "Both checksum values ARE equal!"); 
     int status1 = 0; 
     System.exit(status1); 
    } else { 
     JOptionPane.showMessageDialog(null, "Both checksum values NOT equal"); 
     int status2 = 0; 
     System.exit(status2); 
    } 

} catch (IOException e) { 
     System.out.println("IO Exception. Could not read file!"); 
} 
    return null; 
} 

}

3

Поскольку вы не указали где "во 2-м, а петля" вы получите NPE, я 'просто напишу BufferedReader#readLine():

Возвраты: Строка, содержащая содержимое строки, не включая линию прекращение символов, или нулевую если конец потока достигнут

Кроме того, вы используете frame2 переменными мы не видели инициализированы.

+0

+1 - 'null' из' readLine() 'является наиболее вероятной причиной проблемы NPE OP. И даже если фактическая причина - это что-то еще, это * потенциальная причина ... в зависимости от того, что находится во входном потоке. –

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