简体   繁体   English

用文本文件中的一行(字符串)填充数组的每个槽

[英]Filling each slot of an array with a line (String) from a text file

I have a text file list of thousands of String (3272) and I want to put them each into a slot of an Array so that I can use them to be sorted out.我有一个包含数千个字符串(3272)的文本文件列表,我想将它们分别放入一个数组的插槽中,以便我可以使用它们进行排序。 I have the sorting part done I just need help putting each line of word into an array.我已经完成了排序部分,我只需要帮助将每一行单词放入一个数组中。 This is what I have tried but it only prints the last item from the text file.这是我尝试过的,但它只打印文本文件中的最后一项。

public static void main(String[] args) throws IOException 
{
    FileReader fileText = new FileReader("test.txt");
    BufferedReader scan = new BufferedReader (fileText);
    String line;
    String[] word = new String[3272];
    
    Comparator<String> com = new ComImpl();
    
    while((line = scan.readLine()) != null)
    {
        for(int i = 0; i < word.length; i++)
        {
            word[i] = line;
        }
    }
    
    
    Arrays.parallelSort(word, com);

    
    for(String i: word)
    {
        System.out.println(i);
    }
}

Each time you read a line , you assign it to all of the elements of word .每次阅读line时,都将其分配给word所有元素。 This is why word only ends up with the last line of the file.这就是为什么word只以文件的最后一行结尾的原因。

Replace the while loop with the following code.用以下代码替换while循环。

    int next = 0;
    while ((line = scan.readLine()) != null) word[next++] = line;

Try this.尝试这个。

Files.readAllLines(Paths.get("test.txt"))
    .parallelStream()
    .sorted(new ComImpl())
    .forEach(System.out::println);

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

相关问题 Java读取文本文件并将每一行另存为新的字符串数组 - Java Reading Text File And Saving Each Line As a New String Array 扫描文件并获取文件中的行数,并将每一行分配给数组中的一个槽 - to scan a file and get the number of lines in the file and also assigning each line to a slot in an array 从文本文件中逐行读取并将每一行保存到数组中的不同单元格 - Read line by line from text file and save each line to different cell in array 从命令行txt.file java填充数组 - filling array from command line txt.file java 意外的输出用从文本文件读取的字符填充数组 - Unexpected output filling an array with characters read from a text file 从文本文件填充布尔二维数组 - Filling boolean 2D array from text file 将输入文件中的每一行添加到数组中 - Adding each line from an input file into an array 将一串数字转换为Java中的数组,其中每个数字都是不同的插槽 - Convert a string of numbers to an array in Java, where each number is a different slot 如何将.txt文件中字符串的每一行中的单个字符扫描到2D数组中? - How do you scan individual characters from each line of string in a .txt file into a 2D array? 从Java文件中读取每个字符串文本 - Read the each string text from file in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM