안녕! 오늘 수업은 편의를 위해 두 부분으로 나뉩니다. 우리는 이전에 다루었던 몇 가지 오래된 주제를 반복하고 몇 가지 새로운 기능을 고려할 것입니다 :) 첫 번째 항목부터 시작하겠습니다. 당신은 이미 여러 번 같은 수업을했습니다
물론
이 일이 일어나려면 무엇이 필요합니까? 우선
BufferedReader
. 나는 당신이 이 말을 잊을 시간이 없었기를 바랍니다.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.in
자세히 읽기 전에 각 구성요소( , InputStreamReader
, BufferedReader
)가 담당하는 내용과 필요한 이유를 기억해 보십시오 . 기억하니? 그렇지 않다면 걱정할 필요가 없습니다. :) 잊어버린 것이 있으면 독자 클래스 전용 강의인 이 강의를 다시 읽어보세요. 우리는 그들 각각이 무엇을 할 수 있는지 간략하게 기억할 것입니다. System.in
— 이것은 키보드에서 데이터를 수신하기 위한 스트림입니다. 원칙적으로 텍스트를 읽는 데 필요한 논리를 구현하는 데는 그것만으로도 충분합니다. 그러나 기억하시겠지만 System.in
바이트만 읽을 수 있고 문자는 읽을 수 없습니다.
public class Main {
public static void main(String[] args) throws IOException {
while (true) {
int x = System.in.read();
System.out.println(x);
}
}
}
이 코드를 실행하고 키릴 문자 "Й"를 입력하면 출력은 다음과 같습니다.
Й
208
153
10
키릴 문자는 메모리에서 2바이트를 차지하며 화면에 표시됩니다. 숫자 10은 줄 바꿈 문자의 십진수 표현입니다. 예를 들어 Enter 키를 누르면 됩니다. 바이트 읽기는 정말 즐겁기 때문에 사용이 System.in
그리 편리하지 않습니다. 키릴 문자(및 기타)를 올바르게 읽기 위해 다음을 InputStreamReader
래퍼로 사용합니다.
public class Main {
public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in);
while (true) {
int x = reader.read();
System.out.println(x);
}
}
}
같은 문자 "Й"를 입력했지만 이번에는 결과가 다릅니다.
Й
1049
10
InputStreamReader
2바이트(208 및 153)를 단일 숫자 1049로 변환했습니다. 이것이 문자를 읽는다는 의미입니다. 1049는 키릴 문자 "Й"에 해당합니다. 우리는 이것이 사실임을 쉽게 확신할 수 있습니다.
public class Main {
public static void main(String[] args) throws IOException {
char x = 1049;
System.out.println(x);
}
}
콘솔 출력:
Й
그리고 forBufferedReader
일반적으로 BufferedAnythingYouWant
버퍼 클래스는 성능을 최적화하는 데 사용됩니다. 데이터 소스(파일, 콘솔, 웹 리소스)에 액세스하는 것은 성능 면에서 상당히 비쌉니다. 따라서 액세스 수를 줄이기 위해 BufferedReader
특수 버퍼에서 데이터를 읽고 축적하고 거기에서 가져옵니다. 결과적으로 데이터 소스에 액세스하는 횟수가 몇 배나 줄어듭니다! 의 또 다른 BufferedReader
기능과 일반 에 비해 장점은 개별 숫자가 아닌 전체 데이터 행을 읽는 InputStreamReader
매우 유용한 방법입니다 . readLine()
물론 이것은 큰 텍스트를 다룰 때 매우 편리합니다. 읽기 라인은 다음과 같습니다.
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
System.out.println ("The user entered the following text:");
System.out.println(s);
reader.close();
}
}
BufferedReader+InputStreamReader is faster than InputStreamReader alone
The user entered the following text:
BufferedReader+InputStreamReader is faster than InputStreamReader alone

BufferedReader
매우 유연합니다. 키보드 작업에만 국한되지 않습니다. 예를 들어 필요한 URL을 판독기에 전달하기만 하면 웹에서 직접 데이터를 읽을 수 있습니다.
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("https://www.oracle.com/index.html");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
파일 경로를 전달하여 파일에서 데이터를 읽을 수 있습니다.
public class Main {
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("testFile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
String str;
while ((str = reader.readLine()) != null) {
System.out.println (str);
}
reader.close();
}
}
System.out 교체
이제 이전에 다루지 않은 흥미로운 기능을 살펴보겠습니다. 확실히 기억하고 있듯이System
클래스에는 두 개의 정적 필드 System.in
와 가 있습니다 System.out
. 이 쌍둥이 형제는 스트림 개체입니다. System.in
는 InputStream
. 그리고 System.out
. PrintStream
_ 바로 지금 에 대해 이야기하겠습니다 System.out
. 클래스의 소스 코드 로 이동하면 System
다음과 같이 표시됩니다.
public final class System {
……………...
public final static PrintStream out = null;
…………
}
따라서 System.out
단순히 클래스의 일반 정적 변수입니다System
. 그것에 대해 마법이 없습니다 :) out
변수는 참조입니다 PrintStream
. 다음은 흥미로운 질문입니다. 가 System.out.println()
실행될 때 출력이 정확히 다른 곳이 아닌 콘솔로 이동하는 이유는 무엇입니까? 그리고 이것을 어떻게든 바꿀 수 있습니까? 예를 들어 콘솔에서 데이터를 읽고 텍스트 파일에 쓰고 싶다고 가정합니다. System.out
추가 판독기 및 작성기 클래스가 아닌 사용하여 어떻게든 간단하게 구현할 수 있습니까 ? 실제로 그렇습니다 :) 변수 System.out
에 수식어가 표시되어 있어도 할 수 있습니다 final
! 
PrintStream
현재 객체를 대체할 새 객체가 필요합니다. 에 설정된 현재 객체System
클래스는 기본적으로 우리의 목적에 부합하지 않습니다. 콘솔을 가리킵니다. 데이터의 "대상"인 텍스트 파일을 가리키는 새 파일을 만들어야 합니다. 둘째, 변수에 새 값을 할당하는 방법을 이해해야 합니다 System.out
. 변수가 로 표시되어 있으므로 간단한 대입 연산자를 사용할 수 없습니다 final
. 끝에서 거꾸로 작업합시다. 공교롭게도 System
클래스에는 필요한 메소드가 있습니다 setOut()
. 개체를 가져와 PrintStream
출력 대상으로 설정합니다. 그것이 바로 우리에게 필요한 것입니다! 남은 것은 PrintStream
개체를 만드는 것입니다. 이것도 쉽습니다.
PrintStream filePrintStream = new PrintStream(new File("C:\\Users\\Username\\Desktop\\test.txt"));
전체 코드는 다음과 같습니다.
public class SystemRedirectService {
public static void main(String arr[]) throws FileNotFoundException
{
PrintStream filePrintStream = new PrintStream(new File("C:\\Users\\Username\\Desktop\\test.txt"));
/* Save the current value of System.out in a separate variable so that later
we can switch back to console output */
PrintStream console = System.out;
// Assign a new value to System.out
System.setOut(filePrintStream);
System.out.println("This line will be written to the text file");
// Restore the old value of System.out
System.setOut(console);
System.out.println("But this line will be output to the console!");
}
}
결과적으로 첫 번째 문자열은 텍스트 파일에 작성되고 두 번째 문자열은 콘솔에 표시됩니다 :) 이 코드를 IDE에 복사하여 실행할 수 있습니다. 텍스트 파일을 열면 문자열이 성공적으로 작성된 것을 볼 수 있습니다. :) 이것으로 수업이 끝났습니다. 오늘 우리는 스트림 및 독자와 함께 작업하는 방법을 회상했습니다. 우리는 그들이 서로 어떻게 다른지 기억하고 System.out
거의 모든 수업에서 사용한 의 몇 가지 새로운 기능에 대해 배웠습니다 :) 다음 수업까지!
더 읽어보기: |
---|
GO TO FULL VERSION