java使用InputStream读取文件并封装成对象
文件内容
1930,乌拉圭,乌拉圭
1934,意大利,意大利
1938,法国,意大利
1950,巴西,乌拉圭
1954,瑞士,德国
1958,瑞典,巴西
1962,智利,巴西
1966,英格兰,英格兰
1970,墨西哥,巴西
1974,德国,德国
1978,阿根廷,阿根廷
1982,西班牙,意大利
1986,墨西哥,阿根廷
1990,意大利,德国
1994,美国,巴西
1998,法国,法国
2002,韩国和日本,巴西
2006,德国,意大利
2010,南非,西班牙
2014,巴西,德国
我的文件存放在本地路径E:\demo\message.txt下
要求
创建一个自定义类WorldCup有三个属性,分别存放年份,举办国,胜利国从message.txt里面读取内容,
放到List<WorldCup> list集合里面要求使用InputStream进行读取
代码实现
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class WorldCupClient {
public static void main(String[] args) {
String pathName = "E:/demo/message.txt";
Iterator iterator = getMessageByIO(pathName).iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
/**
* 读取本地文件,获取数据,将其封装成WoeldCup对象,并放入集合
* @param pathName
* @return List<WorldCup>集合
*/
public static List<WorldCup> getMessageByIO(String pathName){
List<WorldCup> list = new ArrayList<>();
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(pathName)))) {
int len = 0;
byte[] buffer = new byte[512];
String message = "";
//获取所有字符
while ((len = bis.read(buffer)) != -1){
message = new String(buffer,0,len,"GBK"); //为防止中文乱码,设置字符集为GBK
}
String[] arr = message.split("\n"); //将获取的字符按行分割
//获取每一行的数据并封装成WorldCup对象
for (int i = 0; i < arr.length; i++) {
String[] line = arr[i].split(",");
WorldCup worldCup = new WorldCup(Integer.parseInt(line[0]),line[1],line[2]);
list.add(worldCup);
}
}catch (IOException e){
e.printStackTrace();
}
return list;
}
}
其中try-with-resource语法在JDK7及以后版本才有,并且只有实现了Closeable接口的类才可以使用,它可以实现资源的自动关闭。在读取数据时,为防止中文乱码,将字符集设置成了GBK。