从文件扫描并将行分隔为不同的字符串

时间:2014-03-13 11:37:42

标签: java string class java.util.scanner filereader

我有一个这样的文本文件:

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

首先是这本书的作者,在|之后出版了书。我想在单独的字符串中读取它们并将它们存储在ArrayList中。这是我到目前为止所得到的:

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());
    }
}

和课本:

   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;


 }
}

它只扫描一个字符,但我需要整个字符串,直到|\n 这是我得到的输出:

Name: ATile: Y
Name: NTile:  
Name: RTile: A
Name: NTile: D
Name:  Tile: |
Name:  Tile: A
Name: nTile: t

2 个答案:

答案 0 :(得分:0)

这可以用不同的方式完成: -

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");
        }

答案 1 :(得分:0)

useDelimiter()方法使用模式表达式和|是模式的特殊逻辑操作,因此,您需要使用\,second |来转义它就是说用\或\ n享受!

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