0

我很抱歉这里的另一篇文章是我的代码:它有效,它打印文本文件,但我不知道如何将第一行与其他行分开。我的意思是我想将第一行的值保存到 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();
    }
}
4

2 回答 2

0

尝试这个

            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);
        }
于 2013-11-03T11:06:00.727 回答
0

只需读取分隔的第一行,然后遍历文件的其余部分。编辑:您可以将您的字符串拆分为一个数组并像这样读取您的整数:

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();
于 2013-11-03T11:02:39.153 回答