如果匹配条件,如何存储文件内容

时间:2015-11-21 17:57:10

标签: java filereader

我在txt文件中有很多专辑,我想在阅读时阅读文件中的每一行。我应检查该行是否以大写字母开头。所以这意味着我应该创建一个类型为Album的新对象,如果该行有" 0"这意味着是跟踪,我应该创建一个Track类型的新对象,例如我想要从文件中添加它并将其存储在我的java程序中的相册:

Pink Floyd:月亮的黑暗面

0:01:30 - 跟我说话

0:06:48 - 脑损伤

。 。 等

这是我的代码,该文件有13张专辑,每张专辑都有很多曲目,包含每首曲目的句号。

 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);

那么如何让程序理解专辑的曲目开始并结束然后将曲目的数组列表传递给专辑对象。

感谢

3 个答案:

答案 0 :(得分:0)

是的,就像这样。

戴夫布鲁贝克四重奏:拿五分

0:06:44 - Blue Rondo a la Turk

0:07:22 - Strange Meadow Lark

0:05:24 - 拿五个

0:04:16 - 拾取棒子

Goldfrapp:超自然

0:03:24 - Ooh La La

0:03:25 - 可爱的2 C U

0:04:41 - 骑白马

答案 1 :(得分:0)

如果你真的想这样做,如果你的文件真的有这个确切的结构,那么这就是一个快速而肮脏的解决方案:

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();
}

你说要打印所有曲目?!

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);
        // .....
    }
}

答案 2 :(得分:0)

您的问题有点难以理解,但我试一试并想象了这个场景。我假设您已经创建了AlbumTrack类,一切正常。我假设您的相册文件如下所示:

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

你要做的就是逐行开始阅读文件,我相信你在我们看不到的代码中的某个地方。对于每一行,您有以下条件,这是正常的

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

每次读一行。如果找到相册,则初始化相册对象并将其存储为艺术家,标题和空的轨道列表。每次找到一个轨道时,检查Album对象是否为空(如果不为null则为当前相册)并检索其轨道列表,向其添加新轨道并将轨道列表设置回Album对象。

我写了下面的代码,假设你有大部分代码,我们在这个问题中看不到。浏览代码,您将了解如何读取行以及如何创建专辑对象,如何在专辑中创建和存储曲目。要测试以下解决方案,请将其复制/粘贴到与类名相同的文件中并执行它,确保您拥有包含相册的album.txt文件。

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());
}
}

您将获得以下输出:

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 ]  

以相同的格式打印从文件中读取的数据。您需要循环播放专辑,并为每个专辑检索曲目列表,然后打印曲目。

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());
    }
}