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

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

Java PrintWriter类

Java PrintWriter类是Writer类的实现。它用于将格式化的对象表示形式打印到文本输出流。

类声明

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

public class PrintWriter extends Writer

PrintWriter类的方法

Method Description
void println(boolean x) It is used to print the boolean value.
void println(char[] x) It is used to print an array of characters.
void println(int x) It is used to print an integer.
PrintWriter append(char c) It is used to append the specified character to the writer.
PrintWriter append(CharSequence ch) It is used to append the specified character sequence to the writer.
PrintWriter append(CharSequence ch, int start, int end) It is used to append a subsequence of specified character to the writer.
boolean checkError() It is used to flushes the stream and check its error state.
protected void setError() It is used to indicate that an error occurs.
protected void clearError() It is used to clear the error state of a stream.
PrintWriter format(String format, Object… args) It is used to write a formatted string to the writer using specified arguments and format string.
void print(Object obj) It is used to print an object.
void flush() It is used to flushes the stream.
void close() It is used to close the stream.

Java PrintWriter示例

让我们看一下使用Java PrintWriter类在控制台和文本文件testout.txt中写入数据的简单示例。

package com.javatpoint;

import java.io.File;
import java.io.PrintWriter;
public class PrintWriterExample {
public static void main(String[] args) throws Exception {
             //Data to write on Console using PrintWriter
  PrintWriter writer = new PrintWriter(System.out); 
  writer.write("Javatpoint provides tutorials of all technology.");   
 writer.flush();
  writer.close();
//Data to write in File using PrintWriter  
  PrintWriter writer1 =null;
   writer1 = new PrintWriter(new File("D:\\testout.txt"));
   writer1.write("Like Java, Spring, Hibernate, Android, PHP etc.");                                         
                         writer1.flush();
     writer1.close();
 }
}

出站

Javatpoint provides tutorials of all technology.

文本文件testout.txt的内容使用Java,Spring,Hibernate,Android,PHP等数据进行设置。