从文件中读取多行中的多个值(Java)

时间:2014-05-08 00:49:38

标签: java file input line-by-line

有没有办法逐行将文件读入Java,每行都有一系列整数(每行不同的整数)。例如:

2 5

1 3 4 5

2 4 8

2 3 5 7 8

我将把每行中的行号和数字读成二维数组。

现在,这是我的代码:

int i=1, j;
try{
  Scanner sc=new Scanner(new File("mapinput.txt"));
  while(sc.hasNext()){
    String line=sc.nextLine();
    while(line!=null){
      j=sc.nextInt();
      Adj[i][j]=1;
    }
    i++;        
  }
} catch(Exception e){System.err.println(e);};

我看到,这段代码的问题在于它在String行之后读取整数一行;我想让它读取那一行中的数字。有没有办法从字符串中读取数字?

更新:
我决定使用StringTokenizer路线;但是,当它到达我的文件的最后一行时,我收到一个java.util.NoSuchElementException:找不到行错误。这是我更新的代码:

try{
  Scanner sc=new Scanner(new File("mapinput.txt"));
  String line=sc.nextLine();
  st=new StringTokenizer(line, " ");
  do{
    while(st.hasMoreTokens()){
      j=Integer.parseInt(st.nextToken());
      Adj[i][j]=1;
    }
    line=sc.nextLine();
    st=new StringTokenizer(line, " ");
    i++;        
  }while(st.hasMoreTokens());
} catch(Exception e){System.err.println(e);};

2 个答案:

答案 0 :(得分:0)

读完一行后,您可以按照

进行操作
String[] ar=line.split(" ");

根据您的要求使用String数组

答案 1 :(得分:0)

查看Java库中的#StringTokenizer类。

您可以轻松地遍历文件并拉出空格分隔的integers。它很好地处理两个+数字整数。

要直接回答您的问题,可以从String获取数字。

查看

Integer.parseInt(String s);  

这会从integer返回String

文档为here

String s1 = "15 ";
String s2 = "03";
int answer = Integer.parseInt(s1.trim()) + Integer.parseInt(s2.trim());
System.out.println(answer);

打印出来:

18