首页 > 解决方案 > 读取 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;
     }
}

标签: javaarraysobjectbufferedreader

解决方案


做类似的事情

 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();

推荐阅读