分割多行分隔符



试图分割包含有关具有不同格式的专辑信息的文本文件。每个专辑由虚线分隔,每个部分的第一行包含有关专辑的信息,其中以冒号分隔,后面的行是专辑中的曲目。

1:Whatever People Say I Am That's What I'm Not:Arctic Monkeys:2006:1.95M
The View from the Afternoon (3:38)
I Bet You Look Good on the Dancefloor (2:53)
----------------------------------------------------------------------------------
2:Different Class:Pulp:1996:1.33M
Mis-Shapes (3:46)
Pencil Skirt (3:11)
----------------------------------------------------------------------------------
20:Konnichiwa:Skepta:2016:207K
Konnichiwa (3:16)
Lyrics (2:36)
----------------------------------------------------------------------------------

我需要帮助将其拆分为一个专辑对象。我已经创建了相册类:

//Album attributes
private String salesRanking;
private String title;
private String artistName;
private String yearRelease;
private String sales;
private String [] tracks; //Array of string to store each track in album
//Album object constructor
public Album (String salesRanking, String title, String artistName, String yearRelease, String sales, String [] tracks){
this.salesRanking = salesRanking;
this.title = title;
this.artistName = artistName;
this.yearRelease = yearRelease;
this.sales = sales;
this.tracks = tracks;
}

分割文本文件并将内容放入专辑对象是我遇到问题的地方。我试着

//Store album objects
ArrayList <String []> bulkAlbum = new ArrayList<>();

try{
//Read file
FileReader freader = new FileReader(albumData);
BufferedReader breader = new BufferedReader(freader);

String line;

while((line=breader.readLine()) != null ){
//Removes empty array
if(line.startsWith("-")){
continue;
}
//Split each album entry
String [] albumDetail = line.split("-");
bulkAlbum.add(albumDetail);
line = "";
}
breader.close();
freader.close();

} catch(IOException ex) {
System.out.println(ex);
}

当我运行代码时,输出显示每一行作为它自己的数组在arrayList中,我意识到我所犯的错误是因为它只是逐行读取,但我不知道从这里去哪里,所以文本文件被整个读取,然后分割或分割为块由虚线创建专辑对象。

用":"分裂是行不通的,因为时间里有冒号。我一直在考虑逻辑,但不知道还有什么可以尝试的。


EDIT -最终解决了这个帮助:如何分割文本文件到对象java

你可以试试-

实现它的逻辑部分,假设您将负责解析和读取文件。

static class Block {
String firstLine;
List<String> tracks;
public Block(String firstLine, List<String> tracks) {
this.firstLine = firstLine;
this.tracks = tracks;
}
}
public static void main(String[] args) {
List<Block> blocks = new ArrayList<>();
try{
//Read file
FileReader freader = new FileReader("../");
BufferedReader breader = new BufferedReader(freader);
List<String> lines = (List<String>) breader.lines();
int i = 0;
while(i < lines.size()){
List<String> addLines = new ArrayList<>();
if(lines.get(i).startsWith("-")){
i++;
} else {
while(!lines.get(i).startsWith("-")){
addLines.add(lines.get(i));
i++;
}
String firstLine = addLines.get(0);
addLines.remove(0);
Block block = new Block(firstLine,addLines);
blocks.add(block);
}
}
breader.close();
freader.close();
} catch(IOException ex) {
System.out.println(ex);
}
List<Album> albums = new ArrayList<>();
for (Block block: blocks) {
//Implement these Methods by yourself
parseFirstLine(block.firstLine);
parseListOfTracks(block.tracks);
}
}

最新更新