如果符合条件,如何存储文件内容

how to store file contents if match a condition

我在 txt 文件中有很多相册,我想边读边读文件中的每一行。我应该检查该行是否以大写字母开头。所以这意味着我应该创建专辑类型的新对象,如果带有“0”的线星表示是曲目,我应该创建曲目类型的新对象等等,例如我想从文件中添加的专辑并将其存储在我的 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);

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

感谢

是这样的。

Dave Brubeck 四重奏:五重奏

0:06:44 - 土耳其人的蓝色回旋曲

0:07:22 - 奇怪的草甸云雀

0:05:24 - 拿五个

0:04:16 - 捡起木棍

戈德弗拉普:超自然

0:03:24 - 哦啦啦

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

0:04:41 - 骑白马

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

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

你的问题有点难懂,我试一试,想象一下场景。我假设您已经创建了 AlbumTrack classes 并且一切正常。我假设您的相册文件如下所示:

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
}

每读一行。如果找到专辑,则初始化专辑 object 并将其存储在艺术家、标题和一个空的曲目列表中。每次找到曲目时,检查专辑 object 是否不为空(如果不为空则为当前专辑)并检索其曲目列表,将新曲目添加到其中并将曲目列表设置回专辑object。

我写了下面的代码,假设你有大部分我们在这个问题中看不到的代码。通过代码,您将了解如何读取一行以及如何创建 object 专辑,如何创建曲目并将其存储在专辑中。要测试以下解决方案,copy/paste 将其保存在与 class 名称相同的文件中并执行它,确保您拥有包含相册的 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());
    }
}