「Java入門」Scanner.useDelimiter( )を利用するサンプルコード

Javaコード
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class SeparatorDemo {

public static void main(String[] args) {
String text
= “tt1\tidNum\tidNum\tidNum\n"
+ “tt2\t1\t2\t3\t4\r\n"
+ “tt3\tA\tB\tC\r"
+ “tt4";

System.out.println(“message1:\n"+text);

List<List<String>> input = new ArrayList<List<String>>();

@SuppressWarnings(“resource")
Scanner sc = new Scanner(text);
while (sc.hasNextLine()) {
@SuppressWarnings(“resource")
Scanner lineSc = new Scanner(sc.nextLine()).useDelimiter(“\t");
List<String> line = new ArrayList<String>();
while (lineSc.hasNext()) {
line.add(lineSc.next());
}
input.add(line);
}
System.out.println(“message2:\n"+input);
}

}

結果
message1:
tt1 idNum idNum idNum
tt2 1 2 3 4
tt3 A B C
tt4
message2:
[[tt1, idNum, idNum, idNum], [tt2, 1, 2, 3, 4], [tt3, A, B, C], [tt4]]

Java

Posted by arkgame