📌  相关文章
📜  Java I/O-StringWriter类

📅  最后修改于: 2020-09-27 07:24:53             🧑  作者: Mango

Java StringWriter类

Java StringWriter类是一个字符流,可从字符串缓冲区收集输出,该缓冲区可用于构造字符串。 StringWriter类继承Writer类。

在StringWriter类中,未使用系统资源(例如网络套接字和文件),因此不需要关闭StringWriter。

Java StringWriter类声明

让我们看一下Java.io.StringWriter类的声明:

public class StringWriter extends Writer

StringWriter类的方法

Method Description
void write(int c) It is used to write the single character.
void write(String str) It is used to write the string.
void write(String str, int off, int len) It is used to write the portion of a string.
void write(char[] cbuf, int off, int len) It is used to write the portion of an array of characters.
String toString() It is used to return the buffer current value as a string.
StringBuffer getBuffer() It is used t return the string buffer.
StringWriter append(char c) It is used to append the specified character to the writer.
StringWriter append(CharSequence csq) It is used to append the specified character sequence to the writer.
StringWriter append(CharSequence csq, int start, int end) It is used to append the subsequence of specified character sequence to the writer.
void flush() It is used to flush the stream.
void close() It is used to close the stream.

Java StringWriter示例

让我们看一下使用BufferedReader从流中读取文件数据的StringWriter的简单示例。

import java.io.*;
public class StringWriterExample {
public static void main(String[] args) throws IOException {
char[] ary = new char[512];
StringWriter writer = new StringWriter();
FileInputStream input = null;
BufferedReader buffer = null;
input = new FileInputStream("D://testout.txt");
buffer = new BufferedReader(new InputStreamReader(input, "UTF-8"));
int x;
while ((x = buffer.read(ary)) != -1) {
                   writer.write(ary, 0, x);
}
System.out.println(writer.toString());
writer.close();
buffer.close();
    }
}

testout.txt:

Javatpoint provides tutorial in Java, Spring, Hibernate, Android, PHP etc.

输出:

Javatpoint provides tutorial in Java, Spring, Hibernate, Android, PHP etc.