我的最终目标是创建一个链接列表,比较一个人的朋友数量(即在下面的列表中Joe有4个朋友而Kay有3个(Joe是最受欢迎的)。列表的数据是导入的从文本文件。我现在的问题是如何读取除文本文件中的第一个字符串值以外的所有内容?
现在文本文件包含以下字符串数据:
Joe Sue Meg Ry Luke Kay Trey Phil George
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String[]> list1 = new LinkedList<String[]>();
// Read the file
try {
BufferedReader in = new BufferedReader(new FileReader("C:\\friendsFile"));
String names;
// Keep reading while there is still more data
while ((names = in.readLine()) != null) {
// Line by line read & add to array
String arr[] = names.split(" ");
String first = arr[0];
System.out.print("\nFirst name: " + first);
if (arr.length > 0)
list1.add(arr);
}
in.close();
// Catch exceptions
} catch (FileNotFoundException e) {
System.out.println("We're sorry, we are unable to find that file: \n" + e.getMessage());
} catch (IOException e) {
System.out.println("We're sorry, we are unable to read that file: \n" + e.getMessage());
}
}
}
答案 0 :(得分:1)
为了保存包含除第一个以外的所有名称的数组,分别为文件中的每一行添加
list1.add(arr);
通过以下内容:
list1.add(Arrays.copyOfRange(arr, 1, arr.length));
答案 1 :(得分:0)
这里只是一个简短的注释,一个名字的文件,其中名字姓和中间名用空格分隔,你将无法进行排序。人们不能假设每个名字只由名字和姓氏组成。也许我通过阅读你的问题弄错了,但你需要更多像CSV文件,其中每个名字都用逗号分隔,然后你可以使用类似的东西:
String[] array = String.split(",");
int numberOfFriend = array.length - 1;
答案 2 :(得分:0)
考虑使用Guava:
Iterable<String> elements = Splitter.on(" ").split(line);
String firstNameInLine = Iterables.getFirst(elements);
Iterable<String> restOfNamesInLine = Iterables.skip(elements, 1);
答案 3 :(得分:0)
你可以做的是在进入while循环之前调用readLine()一次,而不是将它添加到数组中。