【问题标题】:how to store file contents if match a condition如果匹配条件如何存储文件内容
【发布时间】:2015-11-21 17:57:10
【问题描述】:

我在 txt 文件中有很多专辑,我想在阅读时阅读文件中的每一行。我应该检查该行是否以大写字母开头。所以这意味着我应该创建专辑类型的新对象,如果带有“0”的行星表示轨道,我应该为我想从文件中添加的专辑创建新的轨道类型的对象,依此类推并将其存储在我的 java 程序中:

平克·弗洛伊德:月之暗面

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

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

谢谢

【问题讨论】:

  • 您的文件是否包含专辑标题一行,然后曲目是每一行?如果是,那么您能否更新您的问题以反映输入文本文件的实际结构。显示包含专辑的行示例和包含该专辑曲目的行示例。
  • 请在你的句子之间加上标点符号,并很好地格式化你的源代码。这读起来很麻烦。
  • 下次您发布问题时,请确保您阅读了stackoverflow.com/tour,否则您将投反对票而没有答案

标签: java filereader


【解决方案1】:

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

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

【讨论】:

  • 感谢大家的宝贵参与,Raf 我试过你的,现在我的代码可以工作了。
  • 任何人都知道如何逐行打印出数组列表元素。 int size=albumCollection.size(); for(int i=0;i
  • 请不要在评论中复制/粘贴代码。此外,如果您有任何其他问题,请根据 stackoverflow 的指南创建新问题。如果此答案有助于回答您的问题,请将其标记为已接受。
【解决方案2】:

是这样的。

戴夫·布鲁贝克四重奏:五人组

0:06:44 - Blue Rondo a la Turk

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

0:05:24 - 拿五个

0:04:16 - 拿起棍子

Goldfrapp : 超自然

0:03:24 - 哦啦啦

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

0:04:41 - 骑白马

【讨论】:

  • 我的输出问题是每个专辑输出文件中的所有曲目。我想要的是限制输出,这意味着打印带有相关曲目的每张专辑。
  • 萨米,您必须更新您的问题,而不是添加答案答案并在此处包含有关问题的信息。我建议您删除此答案。查看我对您问题的回答,浏览代码,理解它,如有必要,复制/粘贴代码并运行它。确保您的 albums.txt 文件结构如上。
  • 请不要用其他信息回答您自己的问题。您可以随时编辑您的问题。如果您自己找到了解决方案,您应该只回答您自己的问题。
【解决方案3】:

如果您真的想这样做,并且您的文件确实总是具有这种精确的结构,那么一个快速而肮脏的解决方案将是这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-20
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2011-09-25
    相关资源
    最近更新 更多