System.in [중복]과 함께 try-with-resources 사용
그래서 내 IDE는 스캐너를 try with 블록으로 묶지 않으면 불평하지만 닫아야 할 때 닫는 대신 (일단 win = true) 이렇게하면 System.in 스트림을 닫습니다. 어떻게 방지합니까?
public final void turn() {
System.out.println("Enter your next move!");
try (Scanner keyboard = new Scanner(System.in)) {
final String move = keyboard.nextLine();
if (move.isEmpty()) {
won = true;
return;
}
if (!validateFormat(move)) {
System.out.println("Invalid format, try again.");
return;
}
String[] moveAr;
try {
moveAr = move.split(",");
} catch (PatternSyntaxException e) {
System.out.println(e.getMessage());
return;
}
try {
validFields(moveAr);
} catch (InvalidTurnException e) {
System.out.println(e.getMessage());
return;
}
final char colour = spielFeld.getField(getColumn(moveAr[0].charAt(0)),Character.getNumericValue(moveAr[0].charAt(1)) - 1).getColour();
for (final String string : moveAr) {
final int line = Character.getNumericValue(string.charAt(1)) - 1;
final int column = getColumn(string.charAt(0));
spielFeld.cross(column,line);
final int columni = getColumn(string.charAt(0));
if (spielFeld.columnCrossed(columni)) {
points += crossedValues(string.charAt(0));
}
}
if (spielFeld.colourComplete(colour)) {
points += COLOUR_POINTS;
coloursCrossed++;
}
if (coloursCrossed >= 2) {
won = true;
}
}
System.out.println("Momentane Punkte: " + points);
}
답변
Scanner
동일한 입력 스트림을 감싸는 여러 개체 를 사용하지 않는 것이 좋습니다 . (이 경우, System.in
) 그 이유는 스캐너가 기본 스트림의 데이터를 소비하고 버퍼링 할 수 있기 때문입니다. 이는 경우에 따라 데이터가 손실 될 수 있음을 의미합니다. 이 질문에서 더 많은 것을 읽을 수 있습니다 .
여기에서 벗어날 수 있습니다.이 경우 try-with-resources에 래핑하지 않고 Scanner 개체를 닫으면 안됩니다. 이 경우를 사용하여 경고를 억제 할 수 있습니다 @SuppressWarnings("resource")
. 그러나 이것은 나쁜 습관입니다.
대신 Scanner
을 감싸는 단일 전역 개체를 System.in
만든 다음 입력이 필요한 각 메서드에서 새 스캐너를 만드는 대신 매개 변수로이 메서드에 전달하는 것이 좋습니다.
어떻게 방지합니까?
Scanner
객체를 닫지 마십시오 . 즉, Scanner
래핑 중인에 try-with-resources를 사용하지 마십시오 System.in
.
대신 일반적인 "자원"규칙에 대한 특별한 예외이므로 경고를 수락하고 숨 깁니다.
@SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
참고 : Eclipse IDE를 사용하고 있으며 "Surround with try-with-resources"는 경고를 수정하는 첫 번째 옵션 일뿐입니다.
