0

I'm trying to read the contents of a text file into a list view. The text file is in the format

Item 1
Subitem1 | Subitem2 | Subitem3

Item 2 
Subitem1 | Subitem 2 | Subitem3

Item 3
Subitem1 | Subitem2 | Subitem3

This is the logic I used. Search file for specific item

  while(scanner.hasNextLine())
  {    
     line=scanner.next line();
     if(query.equals(line))
     line = scanner.next line();
  }
  return line;

Take the returned line value and split it into String []

  String[] myArray = returnedLine.split("|");

Convert this into List for the list view

  List<String> disp = new ArrayList<String>();
  disp = Arrays.as list(myArray);

The code works. However, the contents of the list view looks weird, with each alphabet in a new listView row. S on one row, u one the next, followed by b, I, t, e, m and 1. All on separate rows

10
  • Also, I just checked. Whatever the query string is, the return value is always the last line of the file ie, subitema of item 3 Commented May 29, 2013 at 21:26
  • @DevOfZot's answer looks good to me and I think this second problem is because you probably want to do a break; instead of the second line = scanner.nextLine(); in your while loop. Commented May 29, 2013 at 21:28
  • I'll have to add the break after scanner.nextLine(); since I want the return to be the line AFTER the item Commented May 29, 2013 at 21:32
  • Edit : nope. Break doesn't solve the issue Commented May 29, 2013 at 21:34
  • Are you sure that's what you want to do? Don't you just want to exit when you've found the line that matches query? Without all your code it's difficult to be sure what you're doing, but in any case your existing code risks a NoSuchElementException as you're calling scanner.nextLine() without checking scanner.hasNextLine() for the second call to scanner.nextLine() Commented May 29, 2013 at 21:38

1 Answer 1

3

The String.split() function takes a regular expression, not a character, and pipe is a special character in regex. Try this:

String[] myArray = returnedLine.split("\\|");

edit: as flightplanner pointer out, your while should probably look like this:

while(scanner.hasNextLine())
{    
    line=scanner.next line();
    if(query.equals(line)) {
        line=scanner.next line();
        break;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

And what about the other issue? It always returns the last line of the file
See flightplanner's comment. You probably only want to call scanner.nextLine() once in the while() statement.
Basically, the string query will be, for example, item 1. When it finds it, it should read the next line @DevOfZot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.