Java : PrintWriter con ejemplos
PrintWriter (Java SE 22 & JDK 22) en Java con ejemplos.
Encontrará ejemplos de código en la mayoría de los métodos de PrintWriter.
Nota :
- Este artículo puede utilizar software de traducción para su comodidad. Consulte también la versión original en inglés.
Summary
Imprime representaciones formateadas de objetos en un flujo de salida de texto. Esta clase implementa todos los métodos de impresión que se encuentran en PrintStream. No contiene métodos para escribir bytes sin formato, para lo cual un programa debería utilizar flujos de bytes sin codificar. (Traducción automática)
final var sw = new StringWriter();
try (final var writer = new PrintWriter(sw)) {
writer.println("abc");
writer.printf("num = %d", 1234);
}
System.out.println(sw);
// Result
// ↓
//abc
//num = 1234
Fields
protected Writer out
La secuencia de salida de caracteres subyacente de este PrintWriter. (Traducción automática)
protected. I think it's rare to create a subclass of this class. Therefore, the code example is omitted.
Fields declared in Writer
Constructors
PrintWriter (File file)
Crea un nuevo PrintWriter, sin vaciado de línea automático, con el archivo especificado. (Traducción automática)
final var file = Path.of("R:", "java-work", "sample.txt");
try (final var writer = new PrintWriter(file.toFile())) {
writer.println("abc");
writer.println(1234);
writer.println("○△×");
}
System.out.print(Files.readString(file));
// Result
// ↓
//abc
//1234
//○△×
PrintWriter (File file, String csn)
Crea un nuevo PrintWriter, sin vaciado automático de líneas, con el archivo y juego de caracteres especificados. (Traducción automática)
System.out.println("default charset : " + Charset.defaultCharset());
final var file = Path.of("R:", "java-work", "sample.txt");
final var csn = "Shift_JIS";
System.out.println("-- write --");
try (final var writer = new PrintWriter(file.toFile(), csn)) {
writer.println("abc");
writer.println(1234);
writer.println("○△×");
}
System.out.print(Files.readString(file, Charset.forName(csn)));
// Result
// ↓
//default charset : UTF-8
//-- write --
//abc
//1234
//○△×
PrintWriter (File file, Charset charset)
Crea un nuevo PrintWriter, sin vaciado automático de líneas, con el archivo y juego de caracteres especificados. (Traducción automática)
System.out.println("default charset : " + Charset.defaultCharset());
final var file = Path.of("R:", "java-work", "sample.txt");
final var charset = Charset.forName("Shift_JIS");
System.out.println("-- write --");
try (final var writer = new PrintWriter(file.toFile(), charset)) {
writer.println("abc");
writer.println(1234);
writer.println("○△×");
}
System.out.print(Files.readString(file, charset));
// Result
// ↓
//default charset : UTF-8
//-- write --
//abc
//1234
//○△×
PrintWriter (OutputStream out)
Crea un nuevo PrintWriter, sin vaciado automático de líneas, a partir de un OutputStream existente. (Traducción automática)
final var out = new ByteArrayOutputStream();
try (final var writer = new PrintWriter(out)) {
writer.println("abc");
writer.println(1234);
}
System.out.println(out);
// Result
// ↓
//abc
//1234
PrintWriter (OutputStream out, boolean autoFlush)
Crea un nuevo PrintWriter a partir de un OutputStream existente. (Traducción automática)
// autoFlush = false
final var out = new ByteArrayOutputStream();
try (final var writer = new PrintWriter(out, false)) {
writer.print("abc");
System.out.println(out.toString().isEmpty());
// Result
// ↓
//true
writer.println("XYZ");
System.out.println(out.toString().isEmpty());
// Result
// ↓
//true
writer.printf("num = %d", 1234);
System.out.println(out.toString().isEmpty());
// Result
// ↓
//true
}
System.out.println(out);
// Result
// ↓
//abcXYZ
//num = 1234
// autoFlush = true
final var out = new ByteArrayOutputStream();
try (final var writer = new PrintWriter(out, true)) {
writer.print("abc");
System.out.println(out.toString().isEmpty());
// Result
// ↓
//true
writer.println("XYZ");
System.out.println(out);
// Result
// ↓
//abcXYZ
writer.printf("num = %d", 1234);
System.out.println(out);
// Result
// ↓
//abcXYZ
//num = 1234
}
System.out.println(out);
// Result
// ↓
//abcXYZ
//num = 1234
PrintWriter (OutputStream out, boolean autoFlush, Charset charset)
Crea un nuevo PrintWriter a partir de un OutputStream existente. (Traducción automática)
Please see also : PrintWriter(OutputStream out, boolean autoFlush)
System.out.println("default charset : " + Charset.defaultCharset());
final var out = new ByteArrayOutputStream();
final var charset = Charset.forName("Shift_JIS");
System.out.println("-- write --");
try (final var writer = new PrintWriter(out, false, charset)) {
writer.println("abc");
writer.println(1234);
writer.println("○△×");
}
System.out.print(out.toString(charset));
// Result
// ↓
//default charset : UTF-8
//-- write --
//abc
//1234
//○△×
PrintWriter (Writer out)
Crea un nuevo PrintWriter, sin vaciado automático de líneas. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.println("abc");
writer.println(1234);
writer.println("○△×");
}
System.out.print(out);
// Result
// ↓
//abc
//1234
//○△×
PrintWriter (Writer out, boolean autoFlush)
Crea un nuevo PrintWriter. (Traducción automática)
// autoFlush = false
final var sw = new StringWriter();
try (final var out = new BufferedWriter(sw);
final var writer = new PrintWriter(out, false)) {
writer.print("abc");
System.out.println(sw.toString().isEmpty());
// Result
// ↓
//true
writer.println("XYZ");
System.out.println(sw.toString().isEmpty());
// Result
// ↓
//true
writer.printf("num = %d", 1234);
System.out.println(sw.toString().isEmpty());
// Result
// ↓
//true
}
System.out.println(sw);
// Result
// ↓
//abcXYZ
//num = 1234
// autoFlush = true
final var sw = new StringWriter();
try (final var out = new BufferedWriter(sw);
final var writer = new PrintWriter(out, true)) {
writer.print("abc");
System.out.println(sw.toString().isEmpty());
// Result
// ↓
//true
writer.println("XYZ");
System.out.println(sw);
// Result
// ↓
//abcXYZ
writer.printf("num = %d", 1234);
System.out.println(sw);
// Result
// ↓
//abcXYZ
//num = 1234
}
System.out.println(sw);
// Result
// ↓
//abcXYZ
//num = 1234
PrintWriter (String fileName)
Crea un nuevo PrintWriter, sin vaciado automático de líneas, con el nombre de archivo especificado. (Traducción automática)
final var file = Path.of("R:", "java-work", "sample.txt");
final var fileName = file.toString();
System.out.println("file name : " + fileName);
System.out.println("-- write --");
try (final var writer = new PrintWriter(fileName)) {
writer.println("abc");
writer.println(1234);
writer.println("○△×");
}
System.out.print(Files.readString(file));
// Result
// ↓
//file name : R:\java-work\sample.txt
//-- write --
//abc
//1234
//○△×
PrintWriter (String fileName, String csn)
Crea un nuevo PrintWriter, sin vaciado automático de líneas, con el nombre de archivo y el juego de caracteres especificados. (Traducción automática)
System.out.println("default charset : " + Charset.defaultCharset());
final var file = Path.of("R:", "java-work", "sample.txt");
final var fileName = file.toString();
System.out.println("file name : " + fileName);
final var csn = "Shift_JIS";
System.out.println("-- write --");
try (final var writer = new PrintWriter(fileName, csn)) {
writer.println("abc");
writer.println(1234);
writer.println("○△×");
}
System.out.print(Files.readString(file, Charset.forName(csn)));
// Result
// ↓
//default charset : UTF-8
//file name : R:\java-work\sample.txt
//-- write --
//abc
//1234
//○△×
PrintWriter (String fileName, Charset charset)
Crea un nuevo PrintWriter, sin vaciado automático de líneas, con el nombre de archivo y el juego de caracteres especificados. (Traducción automática)
System.out.println("default charset : " + Charset.defaultCharset());
final var file = Path.of("R:", "java-work", "sample.txt");
final var fileName = file.toString();
System.out.println("file name : " + fileName);
final var charset = Charset.forName("Shift_JIS");
System.out.println("-- write --");
try (final var writer = new PrintWriter(fileName, charset)) {
writer.println("abc");
writer.println(1234);
writer.println("○△×");
}
System.out.print(Files.readString(file, charset));
// Result
// ↓
//default charset : UTF-8
//file name : R:\java-work\sample.txt
//-- write --
//abc
//1234
//○△×
Methods
PrintWriter append (char c)
Añade el carácter especificado a este escritor. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.append('a').append('b').append('c');
}
System.out.println(out); // abc
PrintWriter append (CharSequence csq)
Añade la secuencia de caracteres especificada a este escritor. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.append("abc").append("-").append("XYZ");
}
System.out.println(out); // abc-XYZ
PrintWriter append (CharSequence csq, int start, int end)
Añade una subsecuencia de la secuencia de caracteres especificada a este escritor. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
final var csq = "abcd";
writer.append(csq, 0, 1).println();
writer.append(csq, 0, 2).println();
writer.append(csq, 0, 3).println();
writer.append(csq, 0, 4).println();
}
System.out.print(out);
// Result
// ↓
//a
//ab
//abc
//abcd
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
final var csq = "abcd";
writer.append(csq, 0, 4).println();
writer.append(csq, 1, 4).println();
writer.append(csq, 2, 4).println();
writer.append(csq, 3, 4).println();
}
System.out.print(out);
// Result
// ↓
//abcd
//bcd
//cd
//d
boolean checkError ()
Limpia la secuencia si no está cerrada y verifica su estado de error. (Traducción automática)
final var file = Path.of("R:", "java-work", "sample.txt");
try (final var out = Files.newBufferedWriter(file);
final var writer = new PrintWriter(out)) {
writer.println("abc");
System.out.println("error : " + writer.checkError());
// Intentionally close the out object to make an error.
System.out.println("-- close --");
out.close();
writer.println("XYZ");
System.out.println("error : " + writer.checkError());
}
// Result
// ↓
//error : false
//-- close --
//error : true
protected void clearError ()
Borra el estado de error de esta transmisión. (Traducción automática)
protected. I think it's rare to create a subclass of this class. Therefore, the code example is omitted.
void close ()
Cierra la transmisión y libera todos los recursos del sistema asociados con ella. (Traducción automática)
final var file = Path.of("R:", "java-work", "sample.txt");
try (final var writer = new PrintWriter(file.toFile())) {
writer.print("abc");
writer.print("XYZ");
}
System.out.println(Files.readString(file)); // abcXYZ
// An example without a try-with-resources statement.
final var file = Path.of("R:", "java-work", "sample.txt");
final var writer = new PrintWriter(file.toFile());
try {
writer.print("abc");
writer.print("XYZ");
} finally {
writer.close();
}
System.out.println(Files.readString(file)); // abcXYZ
void flush ()
Limpia la corriente. (Traducción automática)
final var out = new ByteArrayOutputStream();
try (final var writer = new PrintWriter(out, false)) {
writer.print("abc");
System.out.println(out.toString().isEmpty()); // true
writer.print(123);
System.out.println(out.toString().isEmpty()); // true
writer.flush();
System.out.println(out); // abc123
}
PrintWriter format (String format, Object... args)
Escribe una cadena formateada en este escritor utilizando la cadena de formato y los argumentos especificados. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.format("text = %s%n", "abc");
writer.format("num = %d%n", 1234);
writer.format("X").format("Y").format("Z");
}
System.out.println(out);
// Result
// ↓
//text = abc
//num = 1234
//XYZ
PrintWriter format (Locale l, String format, Object... args)
Escribe una cadena formateada en este escritor utilizando la cadena de formato y los argumentos especificados. (Traducción automática)
System.out.println("locale : " + Locale.getDefault().toLanguageTag());
System.out.println("-- write --");
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
final var time = LocalTime.of(14, 30);
writer.format("%tr%n", time);
writer.format(Locale.JAPANESE, "%tr%n", time);
}
System.out.print(out);
// Result
// ↓
//locale : en-US
//-- write --
//02:30:00 PM
//02:30:00 午後
void print (boolean b)
Imprime un valor booleano. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.print(true);
writer.print(" : ");
writer.print(false);
}
System.out.println(out); // true : false
void print (char c)
Imprime un caracter. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.print('a');
writer.print(" : ");
writer.print('b');
}
System.out.println(out); // a : b
void print (char[] s)
Imprime una matriz de caracteres. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.print(new char[]{'a', 'b', 'c'});
writer.print(" : ");
writer.print(new char[]{'X', 'Y', 'Z'});
}
System.out.println(out); // abc : XYZ
void print (double d)
Imprime un número de punto flotante de doble precisión. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.print(1.234);
writer.print(" : ");
writer.print(7.89e+10);
}
System.out.println(out); // 1.234 : 7.89E10
void print (float f)
Imprime un número de punto flotante. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.print(1.234f);
writer.print(" : ");
writer.print(7.89e+10f);
}
System.out.println(out); // 1.234 : 7.89E10
void print (int i)
Imprime un número entero. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.print(1234);
writer.print(" : ");
writer.print(Integer.MAX_VALUE);
}
System.out.println(out); // 1234 : 2147483647
void print (long l)
Imprime un entero largo. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.print(1234L);
writer.print(" : ");
writer.print(Long.MAX_VALUE);
}
System.out.println(out); // 1234 : 9223372036854775807
void print (Object obj)
Imprime un objeto. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.print(Path.of("R:", "java-work"));
writer.print(" : ");
writer.print(LocalTime.of(14, 30));
}
System.out.println(out); // R:\java-work : 14:30
void print (String s)
Imprime una cadena. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.print("abc");
writer.print(" : ");
writer.print("XYZ");
}
System.out.println(out); // abc : XYZ
PrintWriter printf (String format, Object... args)
Un método conveniente para escribir una cadena formateada en este escritor utilizando la cadena de formato y los argumentos especificados. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.printf("text = %s%n", "abc");
writer.printf("num = %d%n", 1234);
writer.printf("X").printf("Y").printf("Z");
}
System.out.println(out);
// Result
// ↓
//text = abc
//num = 1234
//XYZ
PrintWriter printf (Locale l, String format, Object... args)
Un método conveniente para escribir una cadena formateada en este escritor utilizando la cadena de formato y los argumentos especificados. (Traducción automática)
System.out.println("locale : " + Locale.getDefault().toLanguageTag());
System.out.println("-- write --");
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
final var time = LocalTime.of(14, 30);
writer.printf("%tr%n", time);
writer.printf(Locale.JAPANESE, "%tr%n", time);
}
System.out.print(out);
// Result
// ↓
//locale : en-US
//-- write --
//02:30:00 PM
//02:30:00 午後
void println ()
Termina la línea actual escribiendo la cadena separadora de línea. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.print("abc");
writer.println();
writer.print(123);
}
System.out.println(out);
// Result
// ↓
//abc
//123
void println (boolean x)
Imprime un valor booleano y luego finaliza la línea. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.println(true);
writer.println(false);
}
System.out.print(out);
// Result
// ↓
//true
//false
void println (char x)
Imprime un carácter y luego finaliza la línea. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.println('a');
writer.println('b');
}
System.out.print(out);
// Result
// ↓
//a
//b
void println (char[] x)
Imprime una matriz de caracteres y luego finaliza la línea. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.println(new char[]{'a', 'b', 'c'});
writer.println(new char[]{'X', 'Y', 'Z'});
}
System.out.print(out);
// Result
// ↓
//abc
//XYZ
void println (double x)
Imprime un número de punto flotante de doble precisión y luego finaliza la línea. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.println(1.234);
writer.println(7.89e+10);
}
System.out.print(out);
// Result
// ↓
//1.234
//7.89E10
void println (float x)
Imprime un número de punto flotante y luego finaliza la línea. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.println(1.234f);
writer.println(7.89e+10f);
}
System.out.print(out);
// Result
// ↓
//1.234
//7.89E10
void println (int x)
Imprime un entero y luego finaliza la línea. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.println(1234);
writer.println(Integer.MAX_VALUE);
}
System.out.print(out);
// Result
// ↓
//1234
//2147483647
void println (long x)
Imprime un entero largo y luego finaliza la línea. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.println(1234L);
writer.println(Long.MAX_VALUE);
}
System.out.print(out);
// Result
// ↓
//1234
//9223372036854775807
void println (Object x)
Imprime un objeto y luego finaliza la línea. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.println(Path.of("R:", "java-work"));
writer.println(LocalTime.of(14, 30));
}
System.out.print(out);
// Result
// ↓
//R:\java-work
//14:30
void println (String x)
Imprime una cadena y luego finaliza la línea. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.println("abc");
writer.println("XYZ");
}
System.out.print(out);
// Result
// ↓
//abc
//XYZ
protected void setError ()
Establece el estado de error de la transmisión como verdadero. (Traducción automática)
protected. I think it's rare to create a subclass of this class. Therefore, the code example is omitted.
void write (char[] buf)
Escribe una matriz de caracteres. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.write(new char[]{'a', 'b', 'c'});
writer.write(new char[]{'X', 'Y', 'Z'});
}
System.out.println(out); // abcXYZ
void write (char[] buf, int off, int len)
Escribe una parte de una matriz de caracteres. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
final char[] buf = {'a', 'b', 'c', 'd'};
writer.write(buf, 0, 1);
writer.println();
writer.write(buf, 0, 2);
writer.println();
writer.write(buf, 0, 3);
writer.println();
writer.write(buf, 0, 4);
writer.println();
}
System.out.print(out);
// Result
// ↓
//a
//ab
//abc
//abcd
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
final char[] buf = {'a', 'b', 'c', 'd'};
writer.write(buf, 0, 4);
writer.println();
writer.write(buf, 1, 3);
writer.println();
writer.write(buf, 2, 2);
writer.println();
writer.write(buf, 3, 1);
writer.println();
}
System.out.print(out);
// Result
// ↓
//abcd
//bcd
//cd
//d
void write (int c)
Escribe un solo caracter. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.write('a');
writer.write('b');
writer.write('c');
}
System.out.println(out); // abc
void write (String s)
Escribe una cadena. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
writer.write("abc");
writer.write("XYZ");
}
System.out.println(out); // abcXYZ
void write (String s, int off, int len)
Escribe una parte de una cadena. (Traducción automática)
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
final var s = "abcd";
writer.write(s, 0, 1);
writer.println();
writer.write(s, 0, 2);
writer.println();
writer.write(s, 0, 3);
writer.println();
writer.write(s, 0, 4);
writer.println();
}
System.out.print(out);
// Result
// ↓
//a
//ab
//abc
//abcd
final var out = new StringWriter();
try (final var writer = new PrintWriter(out)) {
final var s = "abcd";
writer.write(s, 0, 4);
writer.println();
writer.write(s, 1, 3);
writer.println();
writer.write(s, 2, 2);
writer.println();
writer.write(s, 3, 1);
writer.println();
}
System.out.print(out);
// Result
// ↓
//abcd
//bcd
//cd
//d
Methods declared in Writer
Related posts
- Ejemplos de API