輸出流是 java.io 包中可用的抽象類。由於它是一個抽象類,為了使用它的函數,我們可以使用它的子類。一些子類是 FileOutputStream、ByteArrayOutputStream、ObjectOutputStream 等。而 String 隻不過是一個字符序列,使用雙引號來表示它。 java.io.ByteArrayOutputStream.toString() 方法使用字符集轉換流。
方法一:
- 創建一個 ByteArrayoutputStream 對象。
- 創建一個字符串變量並初始化它。
- 使用 write 方法將字符串的內容複製到 ByteArrayoutputStream 的對象中。
- 打印它。
例:
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!
方法二:
- 創建一個字節數組並存儲字符的 ASCII 值。
- 創建一個 ByteArrayoutputStream 對象。
- 使用 write 方法將內容從字節數組複製到對象。
- 打印它。
例:
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
相關用法
- Java Java.io.OutputStream用法及代碼示例
- Java InputStream和OutputStream的區別用法及代碼示例
- Java String轉String Array用法及代碼示例
- Java IntStream轉String用法及代碼示例
- Java String轉IntStream用法及代碼示例
- Java String轉Boolean用法及代碼示例
- Java Double轉String用法及代碼示例
- Java String轉Long用法及代碼示例
- Java Date轉String用法及代碼示例
- Java String轉Object用法及代碼示例
- Java InputStream轉String用法及代碼示例
注:本文由純淨天空篩選整理自dadimadhav大神的英文原創作品 Java Program to Convert OutputStream to String。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。