Domanda

well i have this code :

 public void queryForId(){
    String itemName = textField.getText().substring(7, textField.getText().length());
    String br = System.getProperty("line.separator") + " ";
    try {

        once = false;
        item_found = false;

        BufferedReader bure = new BufferedReader(new FileReader("itemList.txt"));

        while (true) {


            String currentLine = bure.readLine();
            String[] split = currentLine.split(" - ", 2);

            if (split[1].equalsIgnoreCase(itemName)) {

                String id = split[0].replace("\uFEFF", "");// removes the BOM.
                textArea.append(br + "[Innovate] The ID(s) of the item '" + itemName + "' is : " + id + ".");
                textField.setText("");
                item_found = true;

            } else {

                if (!once && !item_found) {
                    textArea.append(br + "[Innovate] The Item cannot be found.");
                    textField.setText("");
                    once = true;
                }
            }

        }


    } catch(IOException z){

        z.printStackTrace();
    }
    }

and whenever i use this method, i get my wanted output however it does produce a nullpointer exception and the compiler points to this line :

 String[] split = currentLine.split(" - ", 2);
È stato utile?

Soluzione

If you're going to get text from a BufferedReader, you'd better read the tutorials and look at the examples, since the way to tell when the Stream is done, is it spits out a null, and your code had best be ready for this eventuality. e.g.,

BufferedReader in = ....;
String inputLine = "";

// test for null here when reading in from the Reader
while ((inputLine = in.readLine()) != null) {
    // use inputLine here
}
// close BufferedReader here, usually in a finally block

Altri suggerimenti

Look into BufferedReader readLine() method reference:

Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

So, when the end of in input stream is reached, this function returns null, on which you are trying invoke split() method.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top