當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java OutputStream轉String用法及代碼示例

輸出流是 java.io 包中可用的抽象類。由於它是一個抽象類,為了使用它的函數,我們可以使用它的子類。一些子類是 FileOutputStream、ByteArrayOutputStream、ObjectOutputStream 等。而 String 隻不過是一個字符序列,使用雙引號來表示它。 java.io.ByteArrayOutputStream.toString() 方法使用字符集轉換流。

方法一:

  1. 創建一個 ByteArrayoutputStream 對象。
  2. 創建一個字符串變量並初始化它。
  3. 使用 write 方法將字符串的內容複製到 ByteArrayoutputStream 的對象中。
  4. 打印它。

例:

Input:String = "Hello World"
Output:Hello World

下麵是上述方法的實現:

Java


// Java program to demonstrate conversion
// from outputStream to string
import java.io.*;
class GFG {
    // we know that main will throw
    // IOException so we are ducking it
    public static void main(String[] args)
        throws IOException
    {
        // declaring ByteArrayOutputStream
        ByteArrayOutputStream stream
            = new ByteArrayOutputStream();
        // Initializing string
        String st = "Hello Geek!";
        // writing the specified byte to the output stream
        stream.write(st.getBytes());
        // converting stream to byte array
        // and typecasting into string
        String finalString
            = new String(stream.toByteArray());
        // printing the final string
        System.out.println(finalString);
    }
}
輸出

Hello Geek!

方法二:

  1. 創建一個字節數組並存儲字符的 ASCII 值。
  2. 創建一個 ByteArrayoutputStream 對象。
  3. 使用 write 方法將內容從字節數組複製到對象。
  4. 打印它。

例:

Input:array = [71, 69, 69, 75]
Output:GEEK 

下麵是上述方法的實現:

Java


// Java program to demonstrate conversion
// from outputStream to string
import java.io.*;
class GFG {
    public static void main(String[] args)
        throws IOException
    {
        // Initializing empty string
        // and byte array
        String str = "";
        byte[] bs = { 71, 69, 69, 75, 83, 70, 79,
                      82, 71, 69, 69, 75, 83 };
        // create new ByteArrayOutputStream
        ByteArrayOutputStream stream
            = new ByteArrayOutputStream();
        // write byte array to the output stream
        stream.write(bs);
        // converts buffers using default character set
        // toString is a method for casting into String type
        str = stream.toString();
        // print
        System.out.println(str);
    }
}
輸出
GEEKSFORGEEKS




相關用法


注:本文由純淨天空篩選整理自dadimadhav大神的英文原創作品 Java Program to Convert OutputStream to String。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。