簡體   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