java - 如何从输入文件一次读取两行并将它们添加到对象中?
问题描述
我试图一次从文本文件中读取两行,然后将这些行添加到一个名为 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")
等等。
但是我的代码并没有按照我想要的方式工作,主要是它混淆了字符串inputLine1
和inputLine2
. 例如:代码应该创建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();
}
解决方案
您为 jpg 和 gif 等编写的验证代码看起来不错,但是当它读取两行并将它们连接时,您应该使用一个输入读取行并一次读取两次。然后连接它。那应该工作..
推荐阅读
- python - 新 Python 学习者除数最多的最大数
- java - 随机生成一个范围内的年份
- javascript - 在使用 jQuery 成功进行客户端验证后,如何提交用于服务器端验证的 html 表单?
- azure - 按 DNS 筛选 Azure Application Insights 请求
- c# - 如何在 IIS (Express) 中从远程主机接收 UDP 数据报?
- python - 存储 SSL 套接字连接以实现可重用性 Python
- .net - WPF TabControl - 以编程方式模板和创建选项卡
- html - 悬停在引导模式图像中不起作用
- flutter - Flutter 文档协作
- django - 无法访问/找到静态图像的文件夹