Java Writer toString()方法及示例

Java Writer toString()方法及示例

Java中 Writer 类的 toString() 方法是用来获取这个Writer实例的字符串表示。这个方法不接受任何参数,并返回所需的字符串值。

语法

public String toString()

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

返回值: 该方法返回 一个字符串值 ,即Writer实例的字符串表示。

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

程序 1 :

// Java program to demonstrate
// Writer toString() method
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
 
        try {
 
            // Create a Writer instance
            Writer writer
                = new PrintWriter(System.out);
 
            // 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: java.io.PrintWriter@232204a1

程序2

// Java program to demonstrate
// Writer toString() method
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
 
        try {
 
            // Create a Writer instance
            Writer writer
                = new PrintWriter(System.out);
 
            // 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: java.io.PrintWriter@232204a1

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程