JAVA:如果知道文本文件中有多少个数字,如何读取文本文件并将数据存储到数组中?

时间:2015-02-15 21:30:01

标签: java arrays file text

我有一个看起来像这样的文本文件:

14(*这是跟随的数字的数量)
1
2
3
4
5
6
7
8
9
10个
11个
12个
13个
14

现在我需要使用for循环使用Scanner读取此数据,然后将数字(第一行除外)存储在数组中。

到目前为止我有这个但是我被卡住了:

import java.io.*;
import java.util.*;
public class DirectoryLookupApplication {
   public static void main(String[] args) throws IOException {

   Scanner dataFile = new Scanner(new File("Data3.txt"));
   int numTimes = dataFile.nextInt(); //since the first line tells us how many numbers are in the file-how many times loop will run
   int dataText = new int [numTimes];   
 }
}

2 个答案:

答案 0 :(得分:1)

所以你需要一个执行14次读取的for循环,如:

for (i = 0; i < numTimes; i++)
{
    dataText[i] = dataFile.nextInt();
}

答案 1 :(得分:0)

这是昨天的类似问题(我的答案中的代码已经过测试,如果有效..)你可以根据需要进行转换。

Store 2D array (String) to file and retrieve it