我正在尝试从dat文件中打印特定数据,在这种情况下,此文件包含多部电影中的数据。我将如何仅打印id
和title
列的数据?
movie.dat文件的内容
id title imdbID SpanishTitle
1 Toy story 0114709 juguetes
2 Jumanji 0113497 jumanji
3 Grumpy Old Men 0107050 Dos viejos grunoes
4
我尝试输入代码
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file = new File("movies.dat");
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
while ((line = br.readLine()) != null){
String[] var = line.split(" ");
System.out.println(line);
}
} finally {
br.close();
}
}
}
答案 0 :(得分:1)
您需要分割多个空格,而不仅仅是一个。同样,花了一些时间才知道标题的空格在哪里结束,下一列开始。我使用的imdb功能是7位数字。我还特别注意不要被最后那短行或标题行弄糊涂了。这是怎么出来的。
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args) throws Exception {
File file = new File("movies.dat");
BufferedReader br = new BufferedReader(new FileReader(file));
boolean first = true;
try {
String line;
while ((line = br.readLine()) != null) {
line = line.trim(); //get rid of leading and trailing spaces to be safe
String[]
var = line.split("\\s+"); //split on space or multiple spaces
if (first) {
System.out.println(var [0] + " " +
var [1]); //headers
first = false;
} else if (var.length >= 2) { //enough to write
for (int i = 0; i <
var.length; i++) {
if (var [i].matches("[0-9]+") &&
var [i].length() == 7) { //imdb
break;
}
if (i > 0) {
System.out.print(" ");
}
System.out.print(var [i]);
}
System.out.println();
}
}
} finally {
br.close();
}
}
}