繁体   English   中英

读取文件并将字符串存储到数组中

[英]Reading a file and storing strings into array

我正在尝试从文件(MoviesList)中获取一些数据,并将其存储在变量中,然后进行打印。

该文件包含以下不同的段落:

Fast & Furious7 (2015)
Type: Movie
Director : James Wan 
With : Vin Diesel, Paul Walker, Dwayne Johnson 
Action | Crime | Thriller 137 mins.

这是代码的摘录

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;


public class FlotTest {
    private static BufferedReader fR;


    public void lireLignes(File f) throws IOException{
         fR= new BufferedReader(new FileReader(f));
        String chaine ="";
         do {
         chaine = fR.readLine();
         if (chaine!= null) {

             String [] tab=chaine.split(","); 
             String MovieName=tab[1]; 

        System.out.println(MovieName);



    }
    }while (chaine != null);
         fR.close();

}
}

这是测试班

package testFlot;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class test1 {
    public static void main(String[] args) throws IOException{
        FlotTest t= new FlotTest();
    File f = new File("MoviesList.txt");
       t.lireLignes(f);
    }

我猜您是在将MovieName添加到数组中吗? 如果是这样的话...

声明一个ArrayList<String>变量(在类级别,假设您想在方法之外访问它),以及当前正在调用System.out.println ,只需将它们添加到ArrayList变量即可。

如果您已将行读取并存储到String chaine中,则可以执行以下操作:

   //String chaine="Fast & Furious7 (2015) Type: Movie Director : James Wan With : Vin Diesel, Paul Walker, Dwayne Johnson Action | Crime | Thriller 137 mins";

    String title = chaine.substring(0, chaine.indexOf("(")-1);

    System.out.println(title);

    String year = chaine.substring(chaine.indexOf("(")+1, chaine.indexOf(")"));

    System.out.println(year);

    String type = chaine.substring(chaine.indexOf(":")+2, chaine.indexOf("Director"));

    System.out.println(type);

    String directors = chaine.substring(chaine.indexOf("Director")+11, chaine.indexOf("With"));

    System.out.println(directors);

    //you'll have to figure out a way to parse the actors in depending on how your file is set up
    //it's interesting you don't have a seperator between Actors and the Genre


    //you could create an array
    String[] movie = new String[7];
    movie[0]= title;
    movie[1]=year;
    movie[2]=type;
    movie[3]=directors;



    //I find arraylists easier to deal with so you could create an arraylist
    ArrayList<String> movieList = new ArrayList<String>();
    movieList.add(title);
    movieList.add(year);
    movieList.add(type);
    movieList.add(type);
    movieList.add(directors);

我停下来是因为我有一些工作要完成,但是您可以轻松地为演员,流派和时间长度添加相似的行,然后将它们添加到数组或arrayList中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM