java - 读取 txt 文件并返回一个包含多个字段的对象数组
问题描述
我有一个文本文件,其中每一行都是一个Movie
实例,Movie
对象的字段由制表符分隔。我需要阅读它并返回一个array
包含多个字段的对象(每一行)。我不知道如何制作Movie
对象数组(即Movie[]
)和return
它。
我正在阅读的示例文本文件:
id title price
001 titanic 2
002 lady bird 3
以下是我到目前为止所得到的。
public class Loader {
//private String csvFile;
private static final Resource tsvResource = new ClassPathXmlApplicationContext().getResource("classpath:movies.txt");
private static InputStream movieIS = null;
public Loader() {
try {
movieIS = tsvResource.getInputStream();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Movie[] loadMovies() {
BufferedReader br = null;
String line = "";
String[] tempArray = new String[100];
int id;
String title;
String rating;
String synopsis;
String genre;
String director;
String[] actors;
int price;
int runtime;
int index = 0;
try {
br = new BufferedReader(new InputStreamReader(movieIS));
while ((line = br.readLine()) != null) {
index++;
String[] data = line.split("\\t");
id = Integer.parseInt(data[0]);
title = data[1];
rating = data[2];
synopsis = data[3];
genre = data[4];
director = data[5];
actors = data[6].split(";");
price = Integer.parseInt(data[7]);
runtime = Integer.parseInt(data[8]);
}
String[] lines = new String[index];
for (int i = 0; i < index; i++) {
lines[i] = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return;
}
}
解决方案
做类似的事情
ArrayList <> al = new ArrayList<Movie>();
int index = 0;
try{
br=new BufferedReader(new InputStreamReader(movieIS));
while((line=br.readLine())!=null){
index++;
String[] data=line.split("\\t");
id =Integer.parseInt(data[0]);
title=data[1];
rating=data[2];
synopsis=data[3];
genre=data[4];
director=data[5];
actors=data[6].split(";");
price= Integer.parseInt(data[7]);
runtime=Integer.parseInt(data[8]);
Movie mv = new Movie();
// load into mv
al.add(mv);
}
}
最后像这样返回:
return al.toArray();
推荐阅读
- python - 从相同颜色图的另一种颜色启动 matplotlib 颜色图
- 3d - 3D .gltf 模型的文件大小是如何确定的?
- javascript - 如何使图像 blob URL 持久存在 - 将带有 blob URL 的图像附加到多个 div
- haskell - 将函数应用于列表中的每个元素到另一个列表中的每个元素
- python - Matplotlib venn3 7 个子集之一未显示
- javascript - 解析JSON后消失的元素
- tensorflow - 使用 tensorflow_model_server 和 ssl 配置
- java - 解析图像时出现错误:“org.apache.commons.imaging.ImageReadException:Jpeg 包含多个 Photoshop App13 段”
- google-maps - Flutter 谷歌地图,标记拖动
- c++ - c++ 多线程原子加载/存储