首页 > 解决方案 > 如何从输入文件一次读取两行并将它们添加到对象中?

问题描述

我试图一次从文本文件中读取两行,然后将这些行添加到一个名为 Record 的对象中,如下所示:例如,文本文件内容如下:

course
computer Science
plant
flower.gif
waterfall
A lot of water falling.
waterfall
waterfall.jpg

然后程序应该读取文件的前两行(第 1 行和第 2 行)并创建Record Id1 = new Record("course", "text", "computer science"),然后读取接下来的两行(第 3 和 4 行)并创建Record Id2 = new Record("plant", "image", "flower.gif")等等。

但是我的代码并没有按照我想要的方式工作,主要是它混淆了字符串inputLine1inputLine2. 例如:代码应该创建Record Id1 = new Record("course", "text", "computer science"),它没有,而是创建Record Id1 = new Record("computer science", "text", "")。所以它读入第一行,然后用第二行替换。和同样的事情Record Id2 = new Record("plant", "image", "flower.gif"),它创建Record Id2 = new Record("flower.gif", "image", "")

这是我的代码:

    File file = new File(args[0]);
    BufferedReader inputFile = null;
    try {
        inputFile = new BufferedReader(new FileReader(file));
    } catch (FileNotFoundException e2) {
        e2.printStackTrace();
    }

    String inputLine1, inputLine2;
    OrderedDictionary newTree = new OrderedDictionary();
    try {
        while ((inputLine1 = inputFile.readLine()) != null && (inputLine2 = inputFile.readLine()) != null){
            Record newRecord;
            if(inputLine2.endsWith(".jpg") || inputLine2.endsWith(".gif")){
                newRecord = new Record(new Pair(inputLine1, "image"), inputLine2);
            } else if(inputLine2.endsWith(".wav") || inputLine2.endsWith(".mid")){
                newRecord = new Record(new Pair(inputLine1, "audio"), inputLine2);
            } else {
                newRecord = new Record(new Pair(inputLine1, "text"), inputLine2);
            }

            if(newTree.get(newRecord.getKey()) == null){
                newTree.put(newRecord);
            }
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }

标签: javabufferedreaderreadline

解决方案


您为 jpg 和 gif 等编写的验证代码看起来不错,但是当它读取两行并将它们连接时,您应该使用一个输入读取行并一次读取两次。然后连接它。那应该工作..


推荐阅读