繁体   English   中英

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

[英]LinkedList from .txt file (how to read everything but the first value of each line)

我的最终目标是创建一个链接列表,该列表比较一个人的好友数(即,在下面的列表中,乔有4个朋友,而凯有3个(乔是最受欢迎的朋友)。该列表的数据是从文本中导入的现在我的问题是如何从文本文件中读取除第一个字符串值以外的所有内容?

现在,文本文件具有以下字符串数据:

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));

您可以做的就是在进入while循环之前一次调用readLine(),而不是将其添加到数组中。

只需在此处快速注释一下,您就无法将名字,姓氏和中间名之间用空格分隔的名称文件进行排序。 不能假设每个名字都只由名字​​和姓氏组成。 也许我是通过阅读您的问题来弄错的,但您将需要一个像CSV文件的文件,其中每个名称都用逗号分隔,然后可以使用类似以下的内容:

String[] array = String.split(",");

int numberOfFriend = array.length - 1;

考虑使用番石榴:

 Iterable<String> elements = Splitter.on(" ").split(line);
 String firstNameInLine = Iterables.getFirst(elements);
 Iterable<String> restOfNamesInLine = Iterables.skip(elements, 1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM