【发布时间】:2018-05-06 05:39:04
【问题描述】:
我有一个文本文件,其中每一行是一个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
而不是数组。将此行放在 while 之前: List movies = new ArrayList ();并在里面同时向该列表中添加一个新电影,如下所示:movies.add(new Movie(...)); -
您可以使用 ArrayList 代替数组。这将解决您的问题。
标签: java arrays object bufferedreader