스트림이란?
프로그래밍 세계에서 스트림은 무엇입니까? 왜 필요한가요?
가능하면 유추의 도움으로 친절하게 설명하십시오.
스트림은 일련의 객체 (일반적으로 바이트는 아니지만 반드시 순서는 아님)를 나타내며 순차적으로 액세스 할 수 있습니다. 스트림에서의 일반적인 작업 :
- 1 바이트를 읽습니다. 다음에 읽을 때 다음 바이트를 얻습니다.
- 스트림에서 배열로 몇 바이트를 읽습니다.
- 찾기 (다음에 읽을 때 새 위치에서 바이트를 얻도록 스트림에서 현재 위치를 이동하십시오)
- 1 바이트 쓰기
- 배열에서 스트림으로 몇 바이트 쓰기
- 스트림에서 바이트를 건너 뜁니다 (이것은 읽기와 같지만 데이터를 무시합니다. 또는 원하는 경우 탐색과 같지만 앞으로 나아갈 수 있습니다).
- 바이트를 입력 스트림으로 푸시 백합니다 (이것은 읽기를 위해 "실행 취소"와 같습니다). 스트림을 몇 바이트 백업하면 다음에 읽을 때 볼 수 있습니다. 때때로 파서에 유용합니다 :
- 엿보기 (읽지 않고 바이트를 확인하여 나중에 읽을 수 있도록 스트림에 여전히 있음)
특정 스트림은 읽기 (이 경우 "입력 스트림"), 쓰기 ( "출력 스트림") 또는 둘 다를 지원할 수 있습니다. 모든 스트림을 검색 할 수있는 것은 아닙니다.
푸시 백은 매우 드물지만 내부 버퍼를 보유하는 다른 입력 스트림에 실제 입력 스트림을 래핑하여 스트림에 추가 할 수 있습니다. 버퍼에서 읽기가 이루어지고 뒤로 밀면 데이터가 버퍼에 배치됩니다. 버퍼에 아무것도 없으면 푸시 백 스트림은 실제 스트림에서 읽습니다. 이것은 "스트림 어댑터"의 간단한 예입니다. 입력 스트림의 "끝"에 위치하고 입력 스트림 자체이며 원래 스트림이하지 않은 추가 작업을 수행합니다.
스트림은 파일 (실제로 배열이므로 탐색이 간단 함)을 설명 할 수 있기 때문에 터미널 입력 / 출력 (버퍼링되지 않으면 탐색 할 수 없음), 소켓, 직렬 포트 등을 설명 할 수 있기 때문에 유용한 추상화입니다. "일부 데이터를 원하며 데이터가 어디에서 왔는지 또는 어떻게 가져 왔는지 상관하지 않습니다."또는 "데이터를 생성 할 것입니다. 전적으로 발신자에게 달려 있습니다." 전자는 입력 스트림 매개 변수를 사용하고 후자는 출력 스트림 매개 변수를 사용합니다.
내가 생각할 수있는 가장 좋은 비유는 스트림이 컨베이어 벨트가 당신을 향해오고 나가는 것 (또는 때로는 둘 다)이라는 것입니다. 입력 스트림에서 물건을 꺼내고 출력 스트림에 물건을 놓습니다. 벽에있는 구멍에서 나온 것으로 생각할 수있는 일부 컨베이어는 찾을 수 없거나 읽거나 쓰는 것이 일회성입니다. 일부 컨베이어는 당신 앞에 배치되며, 당신은 읽고 / 쓰기하려는 스트림의 위치를 선택하여 이동할 수 있습니다.
그러나 IRBMe가 말했듯이 물리적 비유보다는 제공하는 작업 (구현에 따라 다르지만 공통점이 많이 있음) 측면에서 스트림을 생각하는 것이 가장 좋습니다. 스트림은 "읽거나 쓸 수있는 것"입니다. 스트림 어댑터 연결을 시작하면 다른 스트림에 연결하는 컨베이어 입력 및 컨베이어 출력이있는 상자로 생각할 수 있습니다. 그런 다음 상자에서 데이터에 대한 변환 (지핑 또는 UNIX 줄 바꿈 변경)을 수행합니다. DOS에, 또는 무엇이든). 파이프는 은유에 대한 또 하나의 철저한 테스트입니다. 여기서 하나의 스트림에 스트림을 작성하여 하나의 스트림에 쓰면 무엇이든 읽을 수 있습니다. 벌레 구멍을 생각하십시오 :-)
스트림은 이미 은유이며 유추이므로 다른 스트림을 povide 할 필요가 없습니다. 기본적으로 물이 실제로 데이터이고 파이프가 스트림 인 물 흐름이있는 파이프로 생각할 수 있습니다. 스트림이 양방향이라면 일종의 양방향 파이프라고 가정합니다. 기본적으로 한 방향 또는 두 방향으로 데이터 흐름 또는 순서가있는 곳에 배치되는 일반적인 추상화입니다.
C #, VB.Net, C ++, Java 등과 같은 언어에서는 스트림 메타포가 여러 가지 용도로 사용됩니다. 파일 스트림은 파일을 열고 스트림에서 읽거나 연속적으로 쓸 수있는 파일 스트림입니다. 스트림에서 읽고 쓰는 스트림은 기본 설정된 네트워크 연결에서 읽고 씁니다. 쓰기 전용 스트림은 일반적 으로이 예제에서와 같이 출력 스트림이라고 하며, 마찬가지로 읽기 전용 스트림은 이 예제 에서와 같이 입력 스트림이라고합니다 .
스트림은 데이터의 변환 또는 인코딩을 수행 할 수 있습니다 ( 예 : .Net 의 SslStream 은 SSL 협상 데이터를 가져 와서 숨길 것입니다. TelnetStream은 Telnet 협상을 숨기고 데이터에 액세스 할 수는 있음) Java의 ZipOutputStream 을 사용하면 zip 파일 형식의 내부에 대해 걱정할 필요없이 zip 아카이브의 파일에 쓸 수 있습니다.
또 다른 일반적인 발견은 바이트 대신 문자열을 작성할 수있는 텍스트 스트림이거나 일부 언어는 기본 유형을 작성할 수있는 2 진 스트림을 제공합니다. 텍스트 스트림에서 흔히 볼 수있는 것은 인코딩해야 할 문자 인코딩입니다.
이 예 에서처럼 일부 스트림은 임의 액세스도 지원 합니다. 반면 네트워크 스트림은 명백한 이유가 없습니다.
- MSDN 은 .Net의 스트림에 대한 좋은 개요를 제공합니다.
- 또한 Sun은 일반 OutputStream 클래스 및 InputStream 클래스에 대한 개요를 제공합니다 .
- C ++에서 istream (입력 스트림), ostream (출력 스트림) 및 iostream (양방향 스트림) 문서는 다음과 같습니다.
UNIX와 같은 운영 체제도 여기에 설명 된대로 프로그램 입력 및 출력과 함께 스트림 모델을 지원합니다 .
지금까지 주어진 답변은 훌륭합니다. 나는 개념이 보편적이기 때문에 스트림이 일련의 바이트가 아니거나 프로그래밍 언어에 국한되지 않는다는 것을 강조하기 위해 다른 것을 제공하고 있습니다 (구현은 독창적 일 수 있습니다). 필자는 종종 SQL, C 또는 Java와 관련하여 온라인에서 많은 설명을 보았습니다. 이는 파일 스트림이 메모리 위치 및 저수준 작업을 처리하는 데 적합합니다. 그러나 그들은 종종 스트림의 개념을 논의하기보다는 파일 스트림을 작성하고 주어진 언어로 잠재적 파일을 조작하는 방법을 다루고 있습니다.
은유
언급했듯이 a stream
는 더 복잡한 무언가의 은유입니다. 상상력을 발휘하기 위해 다른 은유를 제공합니다.
- 빈 수영장에 물을 채우려 고합니다. 이를 달성하는 한 가지 방법은 마개에 호스를 부착하고 호스의 끝을 수영장에 놓고 물을 켜는 것입니다.
호스는 시내입니다
- 마찬가지로 자동차에 가스를 채우려면 가스 펌프로 가서 노즐을 가스 탱크에 넣고 잠금 레버를 꽉 쥐어 밸브를여십시오.
가스가 탱크로 유입되도록하는 호스, 노즐 및 관련 메커니즘
- 출근해야하는 경우 고속도로를 사용하여 집에서 사무실로 운전을 시작합니다.
고속도로는 시내입니다
- 누군가와 대화하고 싶다면 귀로 듣고 입으로 말하십시오.
당신의 귀와 눈은 개울입니다
Hopefully you notice in these examples that the stream metaphors only exist to allow something to travel through it (or on it in the case of the freeway) and do not themselves always poses the thing they are transferring. An important distinction. We don't refer to our ears as a sequence of words. A hose is still a hose if no water is flowing through it, but we have to connect it to a spigot for it do its job correctly. A car is not the only 'kind' of vehicle that can traverse a freeway.
Thus a stream can exist that has no data travelling through it as long as it is connected to a file.
Removing the Abstraction
Next, we need to answer a few questions. I'm going to use files to describe streams so... What is a file? And how do we read a file? I will attempt to answer this while maintaining a certain level of abstraction to avoid unneeded complexity and will use the concept of a file relative to a linux operating system because of its simplicity and accessibility.
What is a file?
A file is an abstraction :)
Or, as simply as I can explain, a file is one part data structure describing the file and one part data which is the actual content.
The data structure part (called an inode in UNIX/linux systems) identities important pieces of information about the content, but does not include the content itself (or a name of the file for that matter). One of the pieces of information it keeps is a memory address to where the content starts. So with a file name (or a hard link in linux), a file descriptor (a numeric file name that the operating system cares about) and a starting location in memory we have something we can call a file.
(the key takeaway is a 'file' is defined by the operating system since it is the OS that ultimately has to deal with it. and yes, files are much more complex).
So far so good. But how do we get the content of the file, say a love letter to your beau, so we can print it?
Reading a file
If we start from the result and move backwards, when we open a file on our computer its entire contents is splashed on our screen for us to read. But how? Very methodically is the answer. The content of the file itself is another data structure. Suppose an array of characters. We can also think of this as a string.
So how do we 'read' this string? By finding its location in memory and iterating through our array of characters, one character at a time until reaching an end of file character. In other words a program.
A stream is 'created' when its program is called and it has a memory location to attach to or connect to. Much like our water hose example, the hose is ineffective if it is not connected to a spigot. In the case of the stream, it must be connected to a file for it to exist.
Streams can be further refined, e.g, a stream to receive input or a stream to send a files contents to standard output. UNIX/linux connects and keeps open 3 filestreams for us right off the bat, stdin (standard input), stdout (standard output) and stderr (standard error). Streams can be built as data structures themselves or objects which allows us to perform more complex operations of the data streaming through them, like opening the stream, closing the stream or error checking the file a stream is connected to. C++'s cin
is an example of a stream object.
Surely, if you so choose, you can write your own stream.
Definition
A stream is a reusable piece of code that abstracts the complexity of dealing with data while providing useful operations to perform on data.
In addition to things mentioned above there is a different kind of streams - as defined in functional programming languages such as Scheme or Haskell - a possibly infinite datastructure which is generated by some function on-demand.
Another analogy: You can't swim against a stream, that's why you just can take the next bit, byte, string or object from the stream, while the already read data is deleted. A one-way-ticket...or basically just a queue without storing persistence.
So do we need queues? You decide.
The word "stream" has been chosen because it represents (in real life) a very similar meaning to what we want to convey when we use it.
Start thinking about the analogy to a water stream. You receive a continuous flow of data, just like water continuously flows in a river. You don't necessarily know where the data is coming from, and most often you don't need to; be it from a file, a socket, or any other source, it doesn't (shouldn't) really matter. This is very similar to receiving a stream of water, whereby you don't need to know where it is coming from; be it from a lake, a fountain, or any other source, it doesn't (shouldn't) really matter. source
참고URL : https://stackoverflow.com/questions/1216380/what-is-a-stream
'development' 카테고리의 다른 글
Bootstrap 4의 '.well'에 해당하는 클래스는 무엇입니까 (0) | 2020.07.29 |
---|---|
프로그램의 단일 인스턴스 만 실행 중인지 확인하십시오 (0) | 2020.07.29 |
파이썬 매개 변수 대 URL 매개 변수 (0) | 2020.07.29 |
에 이미지 삽입 (0) | 2020.07.29 |
Xcode에서 클래스 이름 바꾸기 : Refactor…가 회색으로 표시됩니다 (비활성화 됨). (0) | 2020.07.29 |