📜  Java中的 StringWriter toString() 方法及示例

📅  最后修改于: 2022-05-13 01:55:32.015000             🧑  作者: Mango

Java中的 StringWriter toString() 方法及示例

Java中StringWriter类的toString()方法用于获取此 StringWriter 实例的 String 表示形式。此方法不接受任何参数并返回所需的 String 值。

句法:

public String toString()

参数:此方法接受不接受任何参数。

返回值:此方法返回一个字符串值,它是 StringWriter 实例的字符串表示形式。

下面的方法说明了 toString() 方法的工作:

方案一:

// Java program to demonstrate
// StringWriter toString() method
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
  
            // Create a StringWriter instance
            StringWriter writer
                = new StringWriter();
  
            // Get the String
            // to be written in the stream
            String string = "GeeksForGeeks";
  
            // Write the string
            // to this writer using write() method
            writer.write(string);
  
            System.out.println("String representation: "
                               + writer.toString());
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
String representation: GeeksForGeeks

方案二:

// Java program to demonstrate
// StringWriter toString() method
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
  
            // Create a StringWriter instance
            StringWriter writer
                = new StringWriter();
  
            // Get the String
            // to be written in the stream
            String string = "GFG";
  
            // Write the string
            // to this writer using write() method
            writer.write(string);
  
            System.out.println("String representation: "
                               + writer.toString());
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
String representation: GFG