开发者

Reading from a text file to multiple arrays JAVA

开发者 https://www.devze.com 2023-03-03 16:55 出处:网络
Hi i\'m having a little problem reading from a text file into 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

Hi i'm having a little problem reading from a text file into 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. I have tried putting a write(newlin开发者_JAVA技巧e) 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.

Really am stuck trying to get this to work, i'm quite a beginner at java so any and all help would be appreciated.

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

Example file below :)

testmovie

testmovie2

Firstname Secondname Firstname2 Secondname2

[END EDIT2]


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.

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:

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.


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, e.g.

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.

If each actor listed between two movies belongs to the movie above (e.g. 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 i.e "". From next loop you'll find Actors(create new array of actors from here.

So the take away is readLine Wont Return null for new line it return Empty String "" instead


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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消