Pregunta

I have a text file like this:

AYN RAND | Anthem
William C | The sound
Arthur K | Donelaic year

First is author of the book and after | there goes book. I want to read them in separate strings and store them in an ArrayList. Here is what I got so far:

public static void main(String[] args) {

    String num;
    String num2;
    final List<Book> listofbooks = new ArrayList<>();

    try {
        File file = new File("newfile.txt");
        Scanner input = new Scanner(file);
        input.useDelimiter("|\n");
        while (input.hasNextLine()) {
            num = input.next();  //reads only one char but I need whole string
            num2 = input.next(); //reads only one char but I need whole string
            Book k1 = new Book(num, num2);

            listofbooks.add(k1);
        }
    } catch (FileNotFoundException e) {
        System.err.format("File does not exist");
    }
    for (Book book : listofbooks) {
        System.out.println("Name: " + book.getName() + "Tile: " + book.getTitle());
    }
}

And class book:

   public class Book {

        String name;
        String bookTitle;



        public Book(String name, String bookTitle)
        {
            this.name=name;
            this.bookTitle=bookTitle;
        }
       public String getName()
       {return this.name;
       }
        public String getTitle()
       {return this.bookTitle;


 }
}

It only scans one char, but I need whole string until | or \n Here is the piece of output i get:

Name: ATile: Y
Name: NTile:  
Name: RTile: A
Name: NTile: D
Name:  Tile: |
Name:  Tile: A
Name: nTile: t
¿Fue útil?

Solución

This can be done in different way:-

try {
            File file = new File("newfile.txt");
            Scanner input = new Scanner(file);

            while (input.hasNextLine()) {
              String input1 = input.readLine();// read one line
              String num[] = input1.split("\\|");// split line by "|"
                Book k1 = new Book(num[0], num[1]);

                listofbooks.add(k1);
            }
        } catch (FileNotFoundException e) {
            System.err.format("File does not exist");
        }

Otros consejos

useDelimiter() method use the pattern expression and | is a special logical operation for the pattern, so, you need to escape it with \, second | is to say use a \ or \n enjoy!

input.useDelimiter("\||\n");

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top