如何一次从输入文件读取两行并将其添加到对象?

时间:2018-11-01 22:42:23

标签: java bufferedreader readline

我试图一次从文本文件中读取两行,然后将这些行添加到名为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();
    }

1 个答案:

答案 0 :(得分:0)

您为jpg和gif等编写的验证代码看起来不错,但是当要读取两行并对其进行确认时,您应该使用一条输入读取行并一次性读取两次。然后连接它。应该可以。