ファイルを Java に 1 行ずつ読み込む方法はありますか。各行には一連の整数 (行ごとに異なる量の整数) があります。例えば:
2 5
1 3 4 5
2 4 8
2 3 5 7 8
等
行番号と各行の番号を 2 次元配列に読み取ります。
現在、私が持っているコードは次のとおりです。
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);};
このコードの問題は、文字列行の 1 行後に整数を読み取っていることです。その行の数字を読み取ってほしい。文字列から数値を読み取る方法はありますか?
更新:
StringTokenizer ルートを使用することにしました。ただし、ファイルの最後の行に到達すると、 java.util.NoSuchElementException: No line found エラーが発生します。これが私の更新されたコードです:
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);};