简体   繁体   English

如何在Java中跳过第一个int逐行读取文件到数组?

[英]How to read file line by line to an array in Java skipping first int?

I am trying to read a file in Java and store it into an array. 我试图读取Java中的文件并将其存储到数组中。 Now the problem is that the file has the following structure. 现在的问题是该文件具有以下结构。 I will give 2 example files below: 我将在下面给出2个示例文件:

input file structure 输入文件结构

<number of lines>
<line number> <value>
.
.
.
<line number> <value>

input1.txt input1.txt

5 
1 34
2 19
3 43
4 62
5 36

input2.txt input2.txt

4
1 10.3430423
2 -34.234923
3 -100.39292
4 22

As you can see the file starts with the number of lines(eg 4 or 5). 如您所见,文件以行数开头(例如4或5)。 In the normal input text I have there are more than 100000 lines. 在普通输入文本中,我有超过100000行。

So my code basically grabs the user input, opens the file, create an array size and an array of that size. 因此,我的代码基本上可以获取用户输入,打开文件,创建数组大小和该大小的数组。 Now I am stuck on reading the next line and adding the values to my elements array. 现在,我继续阅读下一行并将值添加到我的elements数组中。 The line number should not be added into the array. 行号不应添加到数组中。 Now as you can see, my elements array is declared as String. 现在您可以看到,我的elements数组被声明为String。 Is it possible to actually read the file, get the type of the value and create an array of that type? 是否可以实际读取文件,获取值的类型并创建该类型的数组? I think it could save from converting from string to int or double or floating? 我认为可以节省从字符串到int或double或float的转换?

Below is my code: 下面是我的代码:

   public static void main(String args[]) throws NumberFormatException, IOException{
        String inFile; //Input file name.
        int filterSize; //Filter size (odd integer >= 3).
        String outFile; //Output file name.
        int arraySize;
        String[] elements;
        int index = 0;

        //Scanner to take input file name, filter size and output file name.
        Scanner keyboardInput = new Scanner(System.in);
        System.out.println("Enter your keyboard input as follows: <data file name> <filter size(odd int >= 3> <output file name>");

        //Assigning values to variables.
        inFile = keyboardInput.next();
        filterSize = keyboardInput.nextInt();
        outFile = keyboardInput.next();


        //Reading file into array using BufferReader
        BufferedReader fileInput = new BufferedReader(new FileReader(inFile));
        arraySize = Integer.parseInt(fileInput.readLine()); //Get Array Size

        elements = new String[arraySize];

        while(fileInput.readLine() != null){
            elements[index] = fileInput.readLine();
            index += 1;
        }               
    }

Any help is appreciated. 任何帮助表示赞赏。 Thanks. 谢谢。

Try doing it like this: 尝试这样做:

    Scanner sc = new Scanner(new File(inFile));
    arraySize = sc.nextInt();
    elements = new String[arraySize];

    while(sc.hasNext())
    {
        sc.nextInt();
        elements[index] = sc.next();
        index += 1;
    }               

You create new Scanner and you can than read integers, booleans and so on, without any converting. 创建新的扫描仪后,无需任何转换即可读取整数,布尔值等。 Because you don't need line of current number, you just read that number and that is it. 因为您不需要当前编号的行,所以只需阅读该编号即可。 You don't need to save it anywhere. 您无需将其保存在任何地方。 Then the next number/string you must save at elements[index] . 然后,下一个数字/字符串必须保存在elements[index] That's it 而已

Go stream-based: 基于流:

Files.lines(pathToFile).skip(1) // skip the line counter. Don't trust input
   .map(line -> line.replaceFirst("\\d+", "")) // remove digits at the start
   .collect(Collectors.toList()); // collect it into a list

You can Store it into an array with .toArray() anyways 您仍然可以使用.toArray()将其存储到数组中

But actually you should do that with a try-with-resources : 但是实际上您应该使用try-with-resources来做到这一点:

try (Stream<String> lines = Files.lines(pathToFile).skip(1)) {
    elements = lines.map(line -> line.replaceFirst("\\d", "")).collect(Collectors.toList());
} catch (IOException e) {
    // sensible handling...
}

Read the number, never use it. 阅读号码,切勿使用。

File file = new File("input1.txt");
Scanner in = new Scanner(file);
int lines = in.nextInt();
int []a = new int[lines];
for(int i = 0; i < lines; i++)
{
 int fakeNumber = in.nextInt();//read it but never used it
 a[i] = in.nextInt(); 
}

You could also use in#hasNextLine() also. 您也可以in#hasNextLine()使用。

The real question here is how to get rid line number and get the value besides it. 真正的问题是如何删除行号并获取其值。

double[] array = .... // initialize your array
int v = 0;
while(file.readLine() != null){
      // your array
      array[v++] = Double.parseDouble(file.readLine().split(" ")[1]);
} 

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

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