如何读取文件的第一行并将它们存储在java中的数组中?

时间:2013-07-13 14:49:19

标签: java

大家好我试图将第一行放入10个整数的数组中。这是我到目前为止所拥有的

public class KnapEncrypt {

public static void main(String[] args) throws FileNotFoundException {
    File file = new File("Testinput.txt");
    Scanner sc = new Scanner(file);

    while(sc.hasNext()){
    int line = sc.nextInt();
    System.out.println(line);
    }



 }
}

这是文件:

191 691 573 337 365 730 651 493 177 354

1000011100

1101000001

0000100010

0100000000

1028

2426

2766

1129

基本上我想要的是将第一行放入一个由10个整数组成的数组,而不是其余的数字

3 个答案:

答案 0 :(得分:3)

BufferedReader reader = new BufferedReader(new FileInputStream(file));
String line = reader.readLine();
String[] lineSplitted = line.split(" ");

答案 1 :(得分:2)

首先从文件中读取您的行:

String line = bufferedReaderForFile.readLine();

然后将其交给scanner

Scanner sc = new Scanner(line);
// your while loop here

答案 2 :(得分:2)

FileInputStream fis = new FileInputStream("your_file_here");

    Scanner scanner = new Scanner(fis);
    String firstLine = scanner.nextLine();

    firstLine.trim();
    String[] data = firstLine.split(" ");

    int[] intData = new int[data.length];

    for (int i = 0; i < intData.length; i++) {
        intData[i] = Integer.parseInt(data[i]);
    }