java - .txt 文件中的 LinkedList(如何读取除每行第一个值之外的所有内容)

标签 java

我的最终目标是创建一个链接列表来比较一个人拥有的 friend 数量(即在下面的列表中,Joe 有 4 个 friend ,而 Kay 有 3 个 friend (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());
        }       
    }
}

最佳答案

为了保存包含除第一个名称之外的所有名称的数组,分别为文件中的每一行,您可以替换

list1.add(arr);

通过以下方式:

list1.add(Arrays.copyOfRange(arr, 1, arr.length));

关于java - .txt 文件中的 LinkedList(如何读取除每行第一个值之外的所有内容),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8099453/

相关文章:

java - 无法将新的 validator 类添加到 Xtext 中的 AbstractJavaValidator

java - 使用 Jsoup 解析表 html

java 8 Stream List<Map> 如何在 groupingBy 后转换 Map

java - Java/Play 中的 JSON 代理!框架

java - 使用消息驱动bean从主题apache apollo获取消息

java - println/打印和间距(java 开始)

Java 字符串——比较 charAt() 和索引运算符 []

java - 关于System.in和stream的问题

java - 手动单击一个按钮,浏览器转到一个新的 url;但是当我使用 webdriver 运行它时,它会打开一个新的浏览器

java - JPanel 由于 componentResize 和长重绘命令而黑屏