当前位置: 动力学知识库 > 问答 > 编程问答 >

java - how to store file contents if match a condition

问题描述:

I have many albums in txt file and i want to read each line in the file while i read. I should check if the line start with Uppercase letter. So that means I should create new object of type Album, and if the line star with "0" that means is track and I should create new object of type Track and so on for an e.g of album which i want tack it from the file and store it in my java program:

Pink Floyd : Dark Side of the Moon

0:01:30 - Speak to me

0:06:48 - Brain Damage

.

.

etc.

And this is my code the file have 13 albums and each has many tracks with the period of every track.

 if(Character.isUpperCase(line.charAt(0))==true) {

String[] token=line.split(":");

artistName=token[0];

albumTitle=token[1];

}

else {

tracks.add(new Track(line));

count2++;

}

album = new Album(artistName,albumTitle,tracks);

albumCollection.add(album);

so how to let the program understand that the start of album's tracks and end and then pass the array list of track to album object.

Thank

网友答案:

Your question is a bit difficult to understand but, I give it a try and imagined the scenario. I assume that you have already created Album and Track classes and everything works. I assume that your albums file looks as follow:

Pink Floyd : Dark Side of the Moon 
0:01:30 - Speak to me 
0:06:48 - Brain Damage
Another artist: Album name
0:02:33 - Whatever 
0:16:21 - Blah Blah
Third artist: Album name
0:02:33 - X 
0:16:21 - Y
0:02:33 - Z 
0:16:21 - A

What you have to do is start reading the file line by line, which I believe that you are doing somewhere in the code that we cannot see. For each line you have the following condition which is fine

//you don't need to add == true in the if condition
if (Character.isUpperCase(line.charAt(0))) {
   //Album found
} else {
   //Track found
}

Every time you read a line. If Album found then you initialize an Album object and store it its artist, title and an empty list of tracks. Every time a track if found, check if the Album object is not null (if not null then it is current album) and retrieve its track list, add the new track to it and set the track list back to the Album object.

I have written the following code, assuming you have majority of it which we cannot see in this question. Go through the code and you will understand how a line is read and how an object of Album is created, how tracks are created and stored in the album. To test the following solution, copy/paste it in file same as class name and execute it, make sure you have the album.txt file containing the album.

import java.util.List;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class Track {
    String track;

    public Track(String track) {
        this.track = track;
    }

    //overriding toString() method for Track class
    public String toString() {
        return track;
    }
}

class Album {
    String artistName;
    String albumTitle;
    List < Track > tracks = new ArrayList < Track > ();

    //Album Constructor
    public Album(String artistName, String albumTitle) {
        this.artistName = artistName;
        this.albumTitle = albumTitle;
    }

    public List < Track > getTracks() {
        return tracks;
    }

    public void setTracks(List < Track > tracks) {
        this.tracks = tracks;
    }

    //overriding the toString method for Album
    public String toString() {
        StringBuilder album = new StringBuilder();
        album.append("Artist name: " + artistName + "\n");
        album.append("\n Album title : " + albumTitle + "\n\n");

        for (int i = 0; i < tracks.size(); i++) {
            album.append("\n Track " + (i + 1) + ":" + tracks.get(i).toString());
        }

        return album.toString();
    }
}

public class ReadAlbums {
    public static void main(String[] args) {
        List < Album > albumsCollection = new ArrayList < Album > ();
        BufferedReader in = null;

        try { in = new BufferedReader(new FileReader("albums.txt"));
            String line;

            List < Track > currentTracks = new ArrayList < Track > ();
            Album album = null;

            while ((line = in .readLine()) != null) {
                //no need to put == true in the if condition 
                if (Character.isUpperCase(line.charAt(0))) {
                    //Album found 

                    String[] token = line.split(":");

                    //If the not the first ever album then add the previous album to the collection 
                    if (album != null) {
                        albumsCollection.add(album);
                    }

                    //new album object is created with artist name and album title 
                    album = new Album(token[0], token[1]);

                    //new empty track list is added to the album object
                    album.setTracks(new ArrayList < Track > ());
                } else {
                    //Track found

                    //retrieve the track from Album album
                    currentTracks = album.getTracks();

                    //Add the track to the list of tracks obtained from album
                    currentTracks.add(new Track(line));

                    //add the updated track list back to the album object
                    album.setTracks(currentTracks);
                }
            }

            //add the last album in the album collections
            if(album != null) {
                albumsCollection.add(album); 
            }

        //close the input stream
        in.close();
    } catch (IOException e) {}


    System.out.println("albums : " + albums.toString());
}
}

You get the following output:

albums : [Artist name: Pink Floyd                                                                                                                                                                              

 Album title :  Dark Side of the Moon                                                                                                                                                                          


 Track 1:0:01:30 - Speak to me                                                                                                                                                                                 
 Track 2:0:06:48 - Brain Damage, Artist name: Another artist                                                                                                                                                   

 Album title :  This is the second album                                                                                                                                                                       


 Track 1:0:02:33 - Whatever                                                                                                                                                                                    
 Track 2:0:16:21 - Blah Blah, Artist name: Third artist                                                                                                                                                        

 Album title :  This is the third album                                                                                                                                                                        


 Track 1:0:02:33 - X ]  

To print the data read from file back in the same format. You need to to loop through albums and for each album retrieve the list of tracks and then print the track.

for(int i = 0; i < albumsCollection.size();i++) {
    Album album = albumsCollection.get(i); 
    System.out.println(album.getArtistName() + ":" + album.getAlbumTitle()); 

    List<Tracks> tracks = album.getTracks(); 
    for(int j = 0; j < tracks.size(); j++) {
        System.out.println(tracks[j].toString());
    }
}
网友答案:

yes it like this.

The Dave Brubeck Quartet : Take Five

0:06:44 - Blue Rondo a la Turk

0:07:22 - Strange Meadow Lark

0:05:24 - Take Five

0:04:16 - Pick Up Sticks

Goldfrapp : Supernature

0:03:24 - Ooh La La

0:03:25 - Lovely 2 C U

0:04:41 - Ride a White Horse

网友答案:

If you really want to do it like this and if your file REALLY always has this exact structure, a quick and dirty solution would be this:

ArrayList<Track> tracks = new ArrayList<Track>();
ArrayList<Album> albumCollection = new ArrayList<Album>();
Album album;
String artistName;
String albumTitle;
String[] token;
BufferedReader br = new BufferedReader(new FileReader("albums.txt"));

try {
    String line = br.readLine();
    while (line != null) {
        if(!Character.isDigit(line.charAt(0)) {
            // there is a problem if your artist name starts with a "0" so add some more checks here
            token = line.split(" : ");
            artistName = token[0];
            albumTitle = token[1];
            if(!tracks.isEmpty()) {
                album = new Album(artistName,albumTitle,tracks); 
                albumCollection.add(album);
                tracks.clear();
            }
        }
        else {
            tracks.add(new Track(line))
        }

        line = br.readLine();
    }
} finally {
    br.close();
}

You said you want to print all tracks?!

for(Album alb : albumCollection) {
    // I dont know about your implementation of the Album class but I assume:
    System.out.println(alb.getTitle());
    System.out.println("##TRACKS###");
    ArrayList<Track> trs = alb.getTracks();
    for(Track tr : trs) {
        String trackName = tr.getTitle(); // I assume again..
        System.out.println(trackName);
        // .....
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: