Java StringWriter close()方法及示例

Java StringWriter close()方法及示例

Java中StringWriter类的close()方法用于关闭写入器。关闭一个写入器会删除其中的任何值或与之相关的任何资源。StringWriter实例一旦关闭就不会再工作。另外,一旦关闭的StringWriter实例不能再被关闭。

语法。

public void close()

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

返回值。这个方法不返回任何值。它只是关闭了流。

下面的程序说明了close()方法的工作原理。

程序1:

// Java program to demonstrate
// StringWriter close() method
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // The string to be written in the Stream
        String str = "GeeksForGeeks";
  
        try {
  
            // Create a StringWriter instance
            StringWriter writer
                = new StringWriter();
  
            // Write the above string to this writer
            // This will put the string in the writer
            // till it is printed on the console
            writer.write(str);
  
            System.out.println(writer.toString());
  
            // Now close the writer
            // using close() method
            writer.close();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

输出:

GeeksForGeeks

程序2。

// Java program to demonstrate
// StringWriter close() method
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
  
            // Create a StringWriter instance
            StringWriter writer
                = new StringWriter();
  
            // Write the char to this writer
            // This will put the char in the writer
            // till it is printed on the console
            writer.write(65);
  
            System.out.println(writer.toString());
  
            // Now close the writer
            // using close() method
            writer.close();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

输出:

A

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程