English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Neste tutorial, vamos aprender o StringWriter do Java e seus subclasses com a ajuda de exemplos.
A classe StringWriter do pacote java.io pode ser usada para escrever dados (em unidades de caractere) no buffer de string.
Ele herda a classe abstrata Writer.
注意Em Java, o buffer de string é considerado uma string mutável. Isso significa que podemos modificar o buffer de string. Para converter o buffer de string em uma string, podemos usar o método toString().
Para criar um StringWriter, devemos primeiro importar o pacote java.io.StringWriter. Após a importação do pacote, podemos criar o escritor de string.
//Cria StringWriter StringWriter output = new StringWriter();
Aqui, criamos um StringWriter com a capacidade do buffer de string padrão. Mas, também podemos especificar a capacidade do buffer de string.
//Cria um StringWriter com a capacidade do buffer de string especificada StringWriter output = new StringWriter(int size);
Aqui, size especifica a capacidade do buffer de string.
StringWriter类为Writer类中提供的不同方法提供实现。
write() - 向字符串写入器写入一个字符
write(char[] array) - 将指定数组中的字符写入写入器
write(String data) - 将指定的字符串写入写入器
import java.io.StringWriter; public class Main { public static void main(String[] args) { String data = "This is the text in the string."; try { //创建具有默认字符串缓冲区容量的StringWriter StringWriter output = new StringWriter(); //将数据写入字符串缓冲区 output.write(data); //打印字符串写入器 System.out.println("StringWriter中的数据: " + "\u3000\u3000" + output); output.close(); } catch(Exception e) { e.getStackTrace(); } } }
Resultados de saída
StringWriter中的数据: " + "This is the text in the string." + "\u3000\u3000"
在上面的示例中,我们创建了一个名为的字符串写入器output。
StringWriter output = new StringWriter();
然后,我们使用该write()方法将字符串数据写入字符串缓冲区。
注意:我们已使用该toString()方法从字符串缓冲区以字符串形式获取输出数据。
getBuffer() -返回字符串缓冲区中存在的数据
toString() -将字符串缓冲区中存在的数据作为字符串返回
例如,
import java.io.StringWriter; public class Main { public static void main(String[] args) { String data = "This is the original data"; try { //创建具有默认字符串缓冲区容量的StringWriter StringWriter output = new StringWriter(); //将数据写入字符串缓冲区 output.write(data); //返回字符串缓冲区 StringBuffer stringBuffer = output.getBuffer(); System.out.println("StringBuffer: " + "\u3000\u3000" + stringBuffer); //以字符串形式返回字符串缓冲区 String string = output.toString(); System.out.println("String: " + "\u3000\u3000" + string); output.close(); } catch(Exception e) { e.getStackTrace(); } } }
Resultados de saída
StringBuffer: This is the original data String: This is the original data
Aqui, usamos o método getBuffer() para obter os dados existentes na área de transferência de string. Além disso, o método toString() também retorna os dados existentes na área de transferência de string na forma de string.
Para fechar o escrevedor de string, podemos usar o método close().
No entanto, o método close() é inválido na classe StringWriter. Mesmo após a chamada do método close(), podemos usar os métodos deste tipo.
Método | Descrição |
---|---|
flush() | Forçar a gravação de todos os dados existentes no escrevedor em uma área de transferência de string |
append() | Inserir o caractere especificado no escrevedor atual |