简体   繁体   English

从文本文件读取到多个 arrays JAVA

[英]Reading from a text file to multiple arrays JAVA

Hi i'm having a little problem reading from a text file into arrays.嗨,我在从文本文件读取到 arrays 时遇到了一点问题。 In my program, it is saved with movies and actors, and when saved, a text file is created with movies first and then actors, with each movie and actor having a seperate line.在我的程序中,它与电影和演员一起保存,保存时,首先创建一个带有电影然后是演员的文本文件,每个电影和演员都有单独的行。

My problem is occuring when trying to read up until a point so that all the movies go in a movies array and all the actors go into an actor array.我的问题是在尝试读取到某个点时发生,以便电影数组中的所有电影 go 和所有演员 go 进入演员数组。 I have tried putting a write(newline) under the last movie in the file and then doing a while loop until the line is null to then end that loop and go onto a new loop for actors until the end of the file but this does not work.我尝试在文件中的最后一部电影下放置一个写入(换行符),然后执行一个while循环,直到该行为 null 以结束该循环,然后将 go 放到一个新的演员循环中,直到文件结束,但这并没有工作。

Really am stuck trying to get this to work, i'm quite a beginner at java so any and all help would be appreciated.真的很难让这个工作,我是 java 的初学者,所以任何和所有的帮助都将不胜感激。

Thanks in advance.提前致谢。

[EDIT] [编辑]

My problem is that everything in the file goes into one array, the movie array.我的问题是文件中的所有内容都进入一个数组,即电影数组。 Instead, I would like the movies to go into the movie array, and the actors to go into the actor array.相反,我想将 go 的电影放入电影数组,并将 go 的演员放入演员数组。 Below is my code for saving and loading the file so far:以下是我到目前为止保存和加载文件的代码:

public void save(String fileName) throws FileNotFoundException {

    try {

        BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
        for ( int i = 0; i < nbrMovies; i++)
        {
        writer.write(movies[i].getName());
        writer.newLine();
        }

        writer.newLine();

        for (int n = 0; n < nbrActors; n++)
        {
            writer.write(actors[n].getFullName());
            writer.newLine();
        }

        writer.close();

    } catch(IOException ex) {
        ex.printStackTrace();
    }
}

public void load(String fileName) throws FileNotFoundException {

    try {
        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        String line = null;
        while ((line = reader.readLine()) != null) {
            addMovie(line);
        }
        reader.close();


    } catch (Exception ex) {

        ex.printStackTrace();
    }

} }

Thanks again:) [END EDIT]再次感谢:) [结束编辑]

[EDIT2] [编辑2]

Example file below:)下面的示例文件:)

testmovie

testmovie2测试电影2

Firstname Secondname Firstname2 Secondname2名 名 名 名 2 名 2 名 2

[END EDIT2] [结束编辑2]

first create the text file where movies and actors are to be stored in seperate line haveing a string attached to it like首先创建将电影和演员存储在单独的行中的文本文件,并附加一个字符串,例如

movie:troy
movie:mission impossible
actor:brad pit
actor:tom cruse

this will help you to identify the line contaning movie or actor then use this code这将帮助您识别包含电影或演员的行,然后使用此代码

FileReader fr=new FileReader("E:\\New folder\\myfile.txt");
BufferedReader br=new BufferedReader(fr);
String str=null;
while((str=br.readLine())!=null)
{
    if(str.contains("movie"))
    {
        //store it into movie array
    }else if(str.contains("actor"))
    {
        //store it into actor array
    }
}

first create the text file where movies and actors are to be stored in seperate line having a identifier string attached to it.首先创建文本文件,其中电影和演员将存储在单独的行中,并附加一个标识符字符串。 like movie:troy movie:mission impossible actor:brad pit actor:tom cruse喜欢电影:特洛伊电影:不可能的任务演员:布拉德皮特演员:汤姆克鲁斯

this will help you to identify the line contaning movie or actor then use this code这将帮助您识别包含电影或演员的行,然后使用此代码

    FileReader fr=new FileReader(filepath);
    BufferedReader br=new BufferedReader(fr);
    String str=null;
    while((str=br.readLine())!=null)
    {
        if(str.contains("movie"))
        {
            //store it into movie array
        }else if(str.contains("actor"))
        {
            //store it into actor array
        }
    }

You can do it by using only one while loop, and a counter.您可以通过仅使用一个 while 循环和一个计数器来完成此操作。

int counter = 0;
while(end of file){
  if(counter%2 == 0){
    // Movie Names, Add to Movie array
  }else{
    // Actor Names, Add to Actor array
  }
}

You need a separator between records, and an empty line should do the trick.您需要记录之间的分隔符,并且空行应该可以解决问题。 The reading algo should go like this:阅读算法应该像这样 go :

List<String> lines = getAllLinesFromFile();  // some magic
Map<String, List<String>> movies = new HashMap<String, List<String>>();

String actualMovieName = "";
for (String line : lines) {
   if (actualMovieName.isEmpty()) {
      // the actual line is movie name
      actualMovieName = line.trim();
      movies.put(actualMovieName, new ArrayList<String>());          
   } else {
      // the actual line is not a movie name
      String actor = line.trim();
      if (!actor.isEmpty() {
        // the actual line is an actor name
        movies.get(actualMovieName).add(line);
      } else {
        // the actual line is a separator (empty line)
        actualMovieName = "";
      }
   }
}

At the end you'll have a map where the key is a movie name (movie names are unique, hopefully.) and the value is a list of actors.最后,您将拥有一个 map,其中键是电影名称(希望电影名称是唯一的),值是演员列表。

Without code or an example of how the file looks like it's hard to give any qualified advice, but you might do something like this:如果没有代码或文件看起来如何的示例,很难给出任何合格的建议,但您可以执行以下操作:

Each line in the file should have an identifier whether it represents a movie or an actor, eg文件中的每一行都应该有一个标识符,无论它代表电影还是演员,例如

M;Terminator
A;Arnold Schwarzenegger
...

Now you could loop through the lines, get the identifier by using String.split(";") and put the movies and actors into their respective arrays.现在您可以遍历这些行,使用String.split(";")获取标识符并将电影和演员放入各自的 arrays 中。

If each actor listed between two movies belongs to the movie above (eg Arnold Schwarzenegger acted in Terminator) you could remember the last movie and assign each new actor to it.如果在两部电影之间列出的每个演员都属于上面的电影(例如阿诺德施瓦辛格在终结者中扮演的角色),您可以记住最后一部电影并将每个新演员分配给它。 When you get a new movie you replace the last saved movie reference.当您获得一部新电影时,您将替换上次保存的电影参考。

I suppose you textfile looks like:我想你的文本文件看起来像:

START开始
Titanic泰坦尼克号
Avatar阿凡达
Matrix矩阵

Keanu Reaves基努·里维斯
John Trovalta约翰·特罗瓦尔塔
Johny Depp约翰尼·德普
END结尾

While u are reding line by line (please refer http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml ) check for empty String ie "".虽然你正在逐行修改(请参阅http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml )检查空字符串,即“”。 From next loop you'll find Actors(create new array of actors from here.在下一个循环中,您将找到 Actors(从这里创建新的 Actor 数组。

So the take away is readLine Wont Return null for new line it return Empty String "" instead所以带走的是 readLine Wont Return null for new line 它返回 Empty String ""

You need to find a condition (such as the empty line you suggested) to terminate the movies loop and then start the actors loop.您需要找到一个条件(例如您建议的空行)来终止电影循环,然后启动演员循环。 Waiting for BufferedReader.readLine() == null won't work because null is only returned at the end of the stream.等待BufferedReader.readLine() == null将不起作用,因为 null 仅在 stream 的末尾返回。

boolean isMovie = true;
while ((line = reader.readLine()) != null)
{
   if(line.equals("")) {
      isMovie = false;
   }

   if(isMovie) {
      addMovie(line);
   } else {
      addActor(line);
   }
}

...alternatively, a better structured data file would make the job easier. ...或者,更好的结构化数据文件将使工作更容易。

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

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