简体   繁体   English

从Java文件中读取数字

[英]Read numbers from file in java

I'm sorry for the other post here is my code: It works, it prints the text file but i don't know how to separate the first row from the others. 对于另一个帖子,我很抱歉,这是我的代码:它可以工作,可以打印文本文件,但是我不知道如何将第一行与其他行分开。 I mean that I want to save the values from the first row into 2 variables and then process the remaining lines. 我的意思是我想将第一行中的值保存到2个变量中,然后处理剩余的行。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class read {
    public static void main (String[] args) throws IOException
    {
        String scan;
        FileReader file = new FileReader("C:\\Users\\W7\\workspace\\SimpleGraph(01-10-13)\\numbers.txt");
        BufferedReader br = new BufferedReader(file);

        while((scan = br.readLine()) != null)
                {
            System.out.println(scan);
                }
        br.close();
    }
}

Just read the first line separated and then iterate over the rest of the file. 只需读取分隔的第一行,然后遍历文件的其余部分。 EDIT: You can split your String into an array and read your Integers like this: 编辑:您可以将您的字符串拆分成一个数组,然后读取您的整数,如下所示:

String scan;
FileReader file = new FileReader("C:\\Users\\W7\\workspace\\SimpleGraph(01-10-13)\\numbers.txt");
BufferedReader br = new BufferedReader(file);
String first = br.readLine();
if ( null != first) {
    System.out.println("First is: " + first);
    String[] numberStrings = first.split(" ");
    int[] numbers = new int[numberStrings.length];
    for (int i = 0; i < numbers.length; i++) {
        numbers[i] = Integer.parseInt(numberStrings[i]);
        System.out.println("Number " + i + " is " + numbers[i]);
    }
    while((scan = br.readLine()) != null) {
        System.out.println(scan);
    }
}
br.close();

Try this 尝试这个

            public static void main(String[] args) throws IOException {
            String scan;
            FileReader file = new FileReader("C:\\Users\\W7\\workspace\\SimpleGraph(01-10-13)\\numbers.txt");
            BufferedReader br = new BufferedReader(file);
            boolean isFirstLine = true;
            int forstNo = 0;
            while ((scan = br.readLine()) != null) {
                if(isFirstLine){
                    forstNo = Integer.parseInt(scan);
                    isFirstLine = false;
                }

                System.out.println(scan);
            }
            br.close();
            System.out.println("first no "+forstNo);
        }

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

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