我在文件中有数据如下:
name: "Clooney, George", release: "2013", movie: "Gravity", imdb: "9",
name: "Pitt, Brad", release: "2004", movie: "Ocean's 12", imdb: "8",
name: "Clooney, George", release: "2004", movie: "Ocean's 12", imdb: "8",
name: "Pitt, Brad", release: "1999", movie: "Fight Club", imdb: "9",
我需要输出如下:
name: "Clooney, George", movie: "Gravity",
name: "Clooney, George", movie: "Ocean's 12",
name: "Pitt, Brad", movie: "Ocean's 12",
name: "Pitt, Brad", movie: "Fight Club",
我对Java很陌生。有人能给我一些关于如何完成这项工作的提示和指示吗?
谢谢, TM
答案 0 :(得分:1)
要执行此操作,请参阅String:
的文档http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
在那里,您可能会发现许多有用的方法可以使用字符串进行任何类型的操作。
要去的算法:
a)将你的字符串分成更小的块
b)使用块
只要你总是省略release和imdb,你也可以使用空行替换(“”)。它会更容易。
答案 1 :(得分:1)
从长远来看,我建议您重新格式化文件中的内容,尝试遵循JSON标准,然后org.json库将能够为您提供很多帮助。否则,您将有一些难看的和硬编码的行进行搜索,解析字符串,将来很难阅读和维护。
JSONObject jsonObj = new JSONObject(\"name\": \"value\", \"release\": "\2013\", \"movie\": \"Gravity\", \"imdb\": \"9\");
另请参阅:org.json库
答案 2 :(得分:1)
public static void main (String [] args){
File file = new File("data.txt");
Scanner scanner;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
line = line.substring(7, line.length()-1);
String name = line.substring(0, line.indexOf("\"")-1);
int index = line.indexOf("movie: \"");
line = line.substring(index+8, line.length()-1);
String movie = line.substring(0, line.indexOf("\"")-1);
System.out.println("name: \"" + name + "\", movie: \"" + movie + "\",");
}
scanner.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答案 3 :(得分:1)
由于这很可能是一次学习练习,这里有一个你可以采取的方法的描述:
ActorMovie
,将演员姓名和电影名称汇总在一起。ActorMovie
对象ActorMovie
个对象 ActorMovie
类可能如下所示:
class ActorMovie {
private String actorName;
private String movieName;
private int releaseYear;
private int imdbRating;
public ActorMovie(
String actorName
, String movieName
, int releaseYear
, int imdbRating) {
this.actorName = actorName;
this.movieName = movieName;
this.releaseYear = releaseYear;
this.imdbRating = imdbRating;
}
public String getActorName() {return actorName;}
public String getMovieName() {return movieName;}
public int getReleaseYear() {return releaseYear;}
public int getImdbRating() {return imdbRating;}
public static ActorMovie parse(String str) {
... // Add code to parse the string in the format that you specified
return new ActorMovie(....);
}
}
你有很多解析选项 - 你可以使用正则表达式来匹配整个字符串,或者逐个字符地遍历字符串,避免用双引号括起来的逗号。
使用List<ActorMovie>
方法对Collections.sort
个对象进行排序:
List<ActorMovie> data = ... // Obtain a list
data.sort(data, new Comparator<ActorMovie> {
public compare(ActorMovie o1, ActorMovie o2) {
return o1.getActorName().compareTo(o2.getActorName());
}
});