' import java.io.BufferedReader;进口java.io.FileReader;进口java.io.IOException;
公共类Dokimi {
private static String line;
public static void main (String[] args) throws IOException
{
int x = 0;
BufferedReader br = new BufferedReader(new FileReader("src/film.txt"));
line = br.readLine();
String[] filmline = new String [1000];
while (line != null) {
line = br.readLine();
filmline[x] = line;
x++;
}
br.close();
for (int i = 0; i<x; i++) // after many tries the last change I made is this. This is the testing class.
{
String [] arr = filmline[i].split(": ");
if ( i == x-1) // I know it isn't the best, maybe not even good but I tried many things and had nothing to lose.
{
for ( String ss : arr) {
String test = ss;
if (test.equals("Dancing With The Dogs "))
{
System.out.println("gotcha!");
}
}
}
}
}
} '那么,我有一个包含一些电影属性的文本文件。例如:
"film id : 1 film title : Pirates Of Hawai film category : action , comedy film description : A pirate from Hawai drinks rum and goes on an adventure to find more rum."
(每个条目在一行中),每次用户试图添加新条目时,我都必须确保该影片尚未在文件中。我尝试了slpit方法(通过使用":"
和擦除"film id"等)和StringTokenizer,但它只适用于一个并由我指定的行,而不是在循环中,以便它可以读取整个文件。
按这里
稍微改变一下行,添加一个":":
"film id : 1 : film title : Pirates Of Hawai : film category : action , comedy : film description : A pirate from Hawai drinks rum and goes on an adventure to find more rum."
你可以尝试这种方法并与你的方法进行比较:(使用existsfilm来验证它是否已经存在,然后添加)
public void showAllFilms(){
ArrayList<String[]> films = getFilms();
for(String[] film : films){
System.out.println("id "+film[0]+"ntitle "+film[1]);
}
}
public existsFilm(String filmName){
ArrayList<String[]> films = getFilms();
for(String[] film : films){
if(film[1].equals(filmName)){
return true;
}
}
return false;
}
public ArrayList<String[]> getFilms(){
ArrayList<String[]> filmList = new ArrayList();
int lineRead = 0;
try{
File file = new File("yourfile.txt");
BufferedReader br = new BufferedReader(new FileReader(file)));
String line;
while ((line = br.readLine()) != null) {
String[] data = line.split(":");
if(data.length > 0){
filmList.add(new String[]{data[1],data[3],data[5],data[7]});
}
lineRead++;
}
}catch(Exception ex){
System.out.println("Error reading line "+lineRead);
ex.printStackTrace(); //very ugly using this (common is logging it)
}
return filmList;
}
不要使用StringTokenizer,它是遗留的,应该支持维护原因,但不应该在新代码中实现。
考虑到每次标记都不同,您可能希望遍历String并在各处使用子字符串,也就是说,假设每行包含相同的标记。
或者,将输入更改为:
"1*夏威夷海盗动作,喜剧一个来自夏威夷的海盗喝朗姆酒和去冒险寻找更多的朗姆酒。"
这样,所有的标记都是相同的,并且您将能够使用split方法。