Java程式:將字串轉換為InputStream


要將給定的字串轉換為InputStream,Java提供了ByteArrayInputStream類,它與名為getBytes()的內建方法一起使用。在顯示較長的輸入字串時,有時需要以較小的單元處理它們。此時,將該字串轉換為InputStream將很有幫助。

在本文中,我們將學習如何使用ByteArrayInputStream類結合示例程式將字串轉換為InputStream。在討論之前,我們需要先學習一些概念:

InputStream

流有兩個基本類,即InputStream類,用於從鍵盤、磁碟檔案等來源獲取輸入;以及OutputStream類,用於將資料顯示或寫入目標。這裡,術語Stream(流)是執行Java中的輸入和輸出操作時使用的抽象。

BufferedReader類

由於InputStream類是一個抽象類,我們需要使用它的子類來實現其功能。其中一個子類是BufferedReader,用於從輸入流(如本地檔案和鍵盤)讀取字元。要使用BufferedReader讀取字串,我們需要建立InputStream類的例項,並將其作為引數傳遞給BufferedReader的建構函式。

getBytes()方法

它是String類的內建方法,用於將字串編碼為位元組陣列。它可以接受一個可選引數來指定字元編碼。如果我們不傳遞任何字元集,它將使用預設字元集。

我們將此位元組陣列作為引數傳遞給ByteArrayInputStream,並將其分配給InputStream類的例項,以便我們可以將字串轉換為InputStream。

Java中的字串到InputStream轉換

讓我們討論一些Java程式,它們演示了字串到InputStream的轉換:

示例1

下面的Java程式演示瞭如何將字串轉換為InputStream。

import java.io.*;
public class Example1 {
   public static void main(String[] args) throws IOException {
      try {
         // initializing a string
         String inputString = "Hello! this is Tutorials Point!!";
         // converting the string to InputStream
         InputStream streamIn = new ByteArrayInputStream(inputString.getBytes());
         // creating instance of BufferedReader 
         BufferedReader bufrd = new BufferedReader(new InputStreamReader(streamIn));
         // New string to store the original string
         String info = null;
         // loop to print the result
         while ((info = bufrd.readLine()) != null) {
            System.out.println(info);
         }
      } catch(Exception exp) { // to handle the exception if occurred
         System.out.println(exp);
      } 
   }
}

上述程式碼的輸出如下:

Hello! this is Tutorials Point!!

示例2

如前所述,我們可以傳遞一個可選引數來為位元組陣列指定字元編碼。在下面的Java程式中,我們將'UTF-8'作為引數傳遞給getBytes()方法。

import java.io.*;
public class Example2 {
   public static void main(String[] args) throws IOException {
      // initializing a string
      String inputString = "Hello! this is Tutorials Point!!";
      // converting the string to InputStream
      InputStream streamIn = new ByteArrayInputStream(inputString.getBytes("UTF-8"));
      // creating instance of BufferedReader 
      BufferedReader bufrd = new BufferedReader(new InputStreamReader(streamIn));
      // New string to store the original string
      String info = null;
      // loop to print the result
      while ((info = bufrd.readLine()) != null) {
         System.out.println(info);
      }
   }
}

上述程式碼產生以下輸出:

Hello! this is Tutorials Point!!

結論

在本文中,我們學習瞭如何在Java中將給定的字串轉換為InputStream。為此,我們討論了兩個使用ByteArrayInputStream類、BufferedReader類和getBytes()方法的Java程式。使用getBytes()方法和ByteArrayInputStream,我們能夠將字串轉換為整數;藉助BufferedReader類,我們讀取了該流。

更新於:2024年7月30日

2K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告