我很抱歉这里的其他帖子是我的代码:它有效,它打印文本文件,但我不知道如何将第一行与其他行分开。我的意思是我想将第一行的值保存为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();
}
}
答案 0 :(得分:0)
只需读取第一行分隔,然后迭代文件的其余部分。 编辑: 您可以将String拆分为数组并按如下方式读取整数:
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();
答案 1 :(得分: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);
}