자바 스캐너로 텍스트 읽기 다음 (패턴 패턴)
-
20-08-2019 - |
문제
스캐너 클래스를 사용하여 다음 (패턴 패턴) 메소드를 사용하여 라인을 읽으려고 노력하고 있습니다. 결장 전에 텍스트를 캡처 한 다음 콜론 다음에 S1 = TextBeforecolon 및 S2 = TextAfterColon을 캡처합니다.
라인은 다음과 같습니다.
뭔가 : 뭔가 셀프
해결책
구체적으로 원하는 것에 따라이 작업을 수행하는 두 가지 방법이 있습니다.
전체 입력을 콜론으로 분할하려면 useDelimiter()
다른 사람들과 마찬가지로 다른 방법은 다음과 같습니다.
// You could also say "scanner.useDelimiter(Pattern.compile(":"))", but
// that's the exact same thing as saying "scanner.useDelimiter(":")".
scanner.useDelimiter(":");
// Examines each token one at a time
while (scanner.hasNext())
{
String token = scanner.next();
// Do something with token here...
}
결장으로 각 선을 분할하려면 사용하기가 훨씬 쉽습니다. String
'에스 split()
방법:
while (scanner.hasNextLine())
{
String[] parts = scanner.nextLine().split(":");
// The parts array now contains ["something", "somethingelse"]
}
다른 팁
나는 스캐너와 함께 패턴을 사용한 적이 없습니다.
나는 항상 줄로 구분기를 변경했습니다.http://java.sun.com/j2se/1.5.0/docs/api/java/util/scanner.html#usedelimiter(java.lang.string)
File file = new File("someFileWithLinesContainingYourExampleText.txt");
Scanner s = new Scanner(file);
s.useDelimiter(":");
while (!s.hasNextLine()) {
while (s.hasNext()) {
String text = s.next();
System.out.println(text);
}
s.nextLine();
}
제휴하지 않습니다 StackOverflow