[英]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.