Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

문자열을 InputStream으로 변환하는 Java 프로그램

<시간/>

이 기사에서는 문자열을 inputStream으로 변환하는 방법을 이해할 것입니다. 문자열은 하나 이상의 문자를 포함하고 큰따옴표(" ")로 묶인 데이터 유형입니다. InputStream 클래스는 바이트의 입력 스트림을 나타내는 모든 클래스의 수퍼 클래스입니다.

아래는 동일한 데모입니다 -

입력이 다음과 같다고 가정 -

Input string: Java Program

원하는 출력은 -

The number of bytes available at the beginning: 12
The number of bytes available at the end: 10

알고리즘

Step 1 - START
Step 2 - Declare string namely input_string, an object of InputStream namely input_stream.
Step 3 - Define the values.
Step 4 - Use the function read() to read the bytes and .available() to fetch the available bytes.
Step 5 - Display the result
Step 6 - Stop

예시 1

여기에서 모든 작업을 'main' 기능 아래에 묶습니다.

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class Demo {
   public static void main(String args[]) {
      String input_string = "Java Program";
      System.out.println("The string is defined as: " + input_string);
      try {
         InputStream input_stream = new ByteArrayInputStream(input_string.getBytes(StandardCharsets.UTF_8));
         System.out.println("The number of bytes available at the beginning: " + input_stream.available());
         input_stream.read();
         input_stream.read();
         System.out.println("The number of bytes available at the end: " + input_stream.available());
         input_stream.close();
      }
      catch (Exception e) {
         e.getStackTrace();
      }
   }
}

출력

The string is defined as: Java Program
The number of bytes available at the beginning: 12
The number of bytes available at the end: 10

예시 2

여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class Demo {
   static void check_bytes(String input_string){
      try {
         InputStream input_stream = new ByteArrayInputStream(input_string.getBytes(StandardCharsets.UTF_8));
         System.out.println("The number of bytes available at the beginning: " + input_stream.available());
         input_stream.read();
         input_stream.read();
         System.out.println("The number of bytes available at the end: " + input_stream.available());
         input_stream.close();
      }
      catch (Exception e) {
         e.getStackTrace();
      }
   }
   public static void main(String args[]) {
      String input_string = "Java Program";
      System.out.println("The string is defined as: " + input_string);
      check_bytes(input_string);
   }
}

출력

The string is defined as: Java Program
The number of bytes available at the beginning: 12
The number of bytes available at the end: 10