Java PrintWriter
Java PrintWriter类是Writer类的实现。它用于将对象的格式化表示形式打印到文本输出流中。
类声明
让我们看看Java.io.PrintWriter类的声明:
public class PrintWriter extends Writer
PrintWriter类的方法
方法 |
说明 |
void println(boolean x) |
用于打印布尔值。 |
void println(char [] x) |
它用于打印字符的数组。 |
void println(int x) |
它用于打印整数。 |
PrintWriter append(char c) |
用于将指定字符附加到编写器上。 |
PrintWriter append(CharSequence ch) |
用于将指定的字符序列附加到编写器。 |
PrintWriter append(CharSequence ch,int start,int end) |
用于将指定字符的子序列附加到编写器。 |
boolean checkError() |
它用于刷新流并检查其错误状态。 |
protected void setError() |
它用于指示发生错误。 |
protected void clearError() |
它用于清除流的错误状态。 |
PrintWriter format(String format, Object... args) |
它用于使用指定的参数和格式字符串将格式化的字符串写入编写器。 |
void print(Object obj) |
它用于打印对象。 |
void flush() |
它用于刷新流。 |
void close() |
它用于关闭流。 |
Java PrintWriter示例
让我们看一下在
控制台和
上写入数据的简单示例。使用Java PrintWriter类>文本文件testout.txt 。
package com.lidihuo;
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("lidihuo 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();
}
}
出站
lidihuo provides tutorials of all technology.
文本文件
testout.txt 的内容是使用数据
设置的,例如Java,Spring,Hibernate,Android,PHP等。