[英]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.