Java中的PrintWriter 介绍_动力节点Java学院整理
PrintWriter介绍
PrintWriter是字符类型的打印输出流,它继承于Writer。
PrintStream用于向文本输出流打印对象的格式化表示形式。它实现在PrintStream中的所有print方法。它不包含用于写入原始字节的方法,对于这些字节,程序应该使用未编码的字节流进行写入。
PrintWriter函数列表
PrintWriter(OutputStreamout)
PrintWriter(OutputStreamout,booleanautoFlush)
PrintWriter(Writerwr)
PrintWriter(Writerwr,booleanautoFlush)
PrintWriter(Filefile)
PrintWriter(Filefile,Stringcsn)
PrintWriter(StringfileName)
PrintWriter(StringfileName,Stringcsn)
PrintWriterappend(charc)
PrintWriterappend(CharSequencecsq,intstart,intend)
PrintWriterappend(CharSequencecsq)
booleancheckError()
voidclose()
voidflush()
PrintWriterformat(Localel,Stringformat,Object...args)
PrintWriterformat(Stringformat,Object...args)
voidprint(floatfnum)
voidprint(doublednum)
voidprint(Stringstr)
voidprint(Objectobj)
voidprint(charch)
voidprint(char[]charArray)
voidprint(longlnum)
voidprint(intinum)
voidprint(booleanbool)
PrintWriterprintf(Localel,Stringformat,Object...args)
PrintWriterprintf(Stringformat,Object...args)
voidprintln()
voidprintln(floatf)
voidprintln(inti)
voidprintln(longl)
voidprintln(Objectobj)
voidprintln(char[]chars)
voidprintln(Stringstr)
voidprintln(charc)
voidprintln(doubled)
voidprintln(booleanb)
voidwrite(char[]buf,intoffset,intcount)
voidwrite(intoneChar)
voidwrite(char[]buf)
voidwrite(Stringstr,intoffset,intcount)
voidwrite(Stringstr)
PrintWriter源码
packagejava.io;
importjava.util.Objects;
importjava.util.Formatter;
importjava.util.Locale;
importjava.nio.charset.Charset;
importjava.nio.charset.IllegalCharsetNameException;
importjava.nio.charset.UnsupportedCharsetException;
publicclassPrintWriterextendsWriter{
protectedWriterout;
//自动flush
//所谓“自动flush”,就是每次执行print(),println(),write()函数,都会调用flush()函数;
//而“不自动flush”,则需要我们手动调用flush()接口。
privatefinalbooleanautoFlush;
//PrintWriter是否右产生异常。当PrintWriter有异常产生时,会被本身捕获,并设置trouble为true
privatebooleantrouble=false;
//用于格式化的对象
privateFormatterformatter;
privatePrintStreampsOut=null;
//行分割符
privatefinalStringlineSeparator;
//获取csn(字符集名字)对应的Chaset
privatestaticCharsettoCharset(Stringcsn)
throwsUnsupportedEncodingException
{
Objects.requireNonNull(csn,"charsetName");
try{
returnCharset.forName(csn);
}catch(IllegalCharsetNameException|UnsupportedCharsetExceptionunused){
//UnsupportedEncodingExceptionshouldbethrown
thrownewUnsupportedEncodingException(csn);
}
}
//将“Writer对象out”作为PrintWriter的输出流,默认不会自动flush,并且采用默认字符集。
publicPrintWriter(Writerout){
this(out,false);
}
//将“Writer对象out”作为PrintWriter的输出流,autoFlush的flush模式,并且采用默认字符集。
publicPrintWriter(Writerout,booleanautoFlush){
super(out);
this.out=out;
this.autoFlush=autoFlush;
lineSeparator=java.security.AccessController.doPrivileged(
newsun.security.action.GetPropertyAction("line.separator"));
}
//将“输出流对象out”作为PrintWriter的输出流,不自动flush,并且采用默认字符集。
publicPrintWriter(OutputStreamout){
this(out,false);
}
//将“输出流对象out”作为PrintWriter的输出流,autoFlush的flush模式,并且采用默认字符集。
publicPrintWriter(OutputStreamout,booleanautoFlush){
//newOutputStreamWriter(out):将“字节类型的输出流”转换为“字符类型的输出流”
//newBufferedWriter(...):为输出流提供缓冲功能。
this(newBufferedWriter(newOutputStreamWriter(out)),autoFlush);
//saveprintstreamforerrorpropagation
if(outinstanceofjava.io.PrintStream){
psOut=(PrintStream)out;
}
}
//创建fileName对应的OutputStreamWriter,进而创建BufferedWriter对象;然后将该BufferedWriter作为PrintWriter的输出流,不自动flush,采用默认字符集。
publicPrintWriter(StringfileName)throwsFileNotFoundException{
this(newBufferedWriter(newOutputStreamWriter(newFileOutputStream(fileName))),
false);
}
//创建fileName对应的OutputStreamWriter,进而创建BufferedWriter对象;然后将该BufferedWriter作为PrintWriter的输出流,不自动flush,采用字符集charset。
privatePrintWriter(Charsetcharset,Filefile)
throwsFileNotFoundException
{
this(newBufferedWriter(newOutputStreamWriter(newFileOutputStream(file),charset)),
false);
}
//创建fileName对应的OutputStreamWriter,进而创建BufferedWriter对象;然后将该BufferedWriter作为PrintWriter的输出流,不自动flush,采用csn字符集。
publicPrintWriter(StringfileName,Stringcsn)
throwsFileNotFoundException,UnsupportedEncodingException
{
this(toCharset(csn),newFile(fileName));
}
//创建file对应的OutputStreamWriter,进而创建BufferedWriter对象;然后将该BufferedWriter作为PrintWriter的输出流,不自动flush,采用默认字符集。
publicPrintWriter(Filefile)throwsFileNotFoundException{
this(newBufferedWriter(newOutputStreamWriter(newFileOutputStream(file))),
false);
}
//创建file对应的OutputStreamWriter,进而创建BufferedWriter对象;然后将该BufferedWriter作为PrintWriter的输出流,不自动flush,采用csn字符集。
publicPrintWriter(Filefile,Stringcsn)
throwsFileNotFoundException,UnsupportedEncodingException
{
this(toCharset(csn),file);
}
privatevoidensureOpen()throwsIOException{
if(out==null)
thrownewIOException("Streamclosed");
}
//flush“PrintWriter输出流中的数据”。
publicvoidflush(){
try{
synchronized(lock){
ensureOpen();
out.flush();
}
}
catch(IOExceptionx){
trouble=true;
}
}
publicvoidclose(){
try{
synchronized(lock){
if(out==null)
return;
out.close();
out=null;
}
}
catch(IOExceptionx){
trouble=true;
}
}
//flush“PrintWriter输出流缓冲中的数据”,并检查错误
publicbooleancheckError(){
if(out!=null){
flush();
}
if(outinstanceofjava.io.PrintWriter){
PrintWriterpw=(PrintWriter)out;
returnpw.checkError();
}elseif(psOut!=null){
returnpsOut.checkError();
}
returntrouble;
}
protectedvoidsetError(){
trouble=true;
}
protectedvoidclearError(){
trouble=false;
}
//将字符c写入到“PrintWriter输出流”中。c虽然是int类型,但实际只会写入一个字符
publicvoidwrite(intc){
try{
synchronized(lock){
ensureOpen();
out.write(c);
}
}
catch(InterruptedIOExceptionx){
Thread.currentThread().interrupt();
}
catch(IOExceptionx){
trouble=true;
}
}
//将“buf中从off开始的len个字符”写入到“PrintWriter输出流”中。
publicvoidwrite(charbuf[],intoff,intlen){
try{
synchronized(lock){
ensureOpen();
out.write(buf,off,len);
}
}
catch(InterruptedIOExceptionx){
Thread.currentThread().interrupt();
}
catch(IOExceptionx){
trouble=true;
}
}
//将“buf中的全部数据”写入到“PrintWriter输出流”中。
publicvoidwrite(charbuf[]){
write(buf,,buf.length);
}
//将“字符串s中从off开始的len个字符”写入到“PrintWriter输出流”中。
publicvoidwrite(Strings,intoff,intlen){
try{
synchronized(lock){
ensureOpen();
out.write(s,off,len);
}
}
catch(InterruptedIOExceptionx){
Thread.currentThread().interrupt();
}
catch(IOExceptionx){
trouble=true;
}
}
//将“字符串s”写入到“PrintWriter输出流”中。
publicvoidwrite(Strings){
write(s,,s.length());
}
//将“换行符”写入到“PrintWriter输出流”中。
privatevoidnewLine(){
try{
synchronized(lock){
ensureOpen();
out.write(lineSeparator);
if(autoFlush)
out.flush();
}
}
catch(InterruptedIOExceptionx){
Thread.currentThread().interrupt();
}
catch(IOExceptionx){
trouble=true;
}
}
//将“boolean数据对应的字符串”写入到“PrintWriter输出流”中,print实际调用的是write函数
publicvoidprint(booleanb){
write(b?"true":"false");
}
//将“字符c对应的字符串”写入到“PrintWriter输出流”中,print实际调用的是write函数
publicvoidprint(charc){
write(c);
}
//将“int数据i对应的字符串”写入到“PrintWriter输出流”中,print实际调用的是write函数
publicvoidprint(inti){
write(String.valueOf(i));
}
//将“long型数据l对应的字符串”写入到“PrintWriter输出流”中,print实际调用的是write函数
publicvoidprint(longl){
write(String.valueOf(l));
}
//将“float数据f对应的字符串”写入到“PrintWriter输出流”中,print实际调用的是write函数
publicvoidprint(floatf){
write(String.valueOf(f));
}
//将“double数据d对应的字符串”写入到“PrintWriter输出流”中,print实际调用的是write函数
publicvoidprint(doubled){
write(String.valueOf(d));
}
//将“字符数组s”写入到“PrintWriter输出流”中,print实际调用的是write函数
publicvoidprint(chars[]){
write(s);
}
//将“字符串数据s”写入到“PrintWriter输出流”中,print实际调用的是write函数
publicvoidprint(Strings){
if(s==null){
s="null";
}
write(s);
}
//将“对象obj对应的字符串”写入到“PrintWriter输出流”中,print实际调用的是write函数
publicvoidprint(Objectobj){
write(String.valueOf(obj));
}
//将“换行符”写入到“PrintWriter输出流”中,println实际调用的是write函数
publicvoidprintln(){
newLine();
}
//将“boolean数据对应的字符串+换行符”写入到“PrintWriter输出流”中,println实际调用的是write函数
publicvoidprintln(booleanx){
synchronized(lock){
print(x);
println();
}
}
//将“字符x对应的字符串+换行符”写入到“PrintWriter输出流”中,println实际调用的是write函数
publicvoidprintln(charx){
synchronized(lock){
print(x);
println();
}
}
//将“int数据对应的字符串+换行符”写入到“PrintWriter输出流”中,println实际调用的是write函数
publicvoidprintln(intx){
synchronized(lock){
print(x);
println();
}
}
//将“long数据对应的字符串+换行符”写入到“PrintWriter输出流”中,println实际调用的是write函数
publicvoidprintln(longx){
synchronized(lock){
print(x);
println();
}
}
//将“float数据对应的字符串+换行符”写入到“PrintWriter输出流”中,println实际调用的是write函数
publicvoidprintln(floatx){
synchronized(lock){
print(x);
println();
}
}
//将“double数据对应的字符串+换行符”写入到“PrintWriter输出流”中,println实际调用的是write函数
publicvoidprintln(doublex){
synchronized(lock){
print(x);
println();
}
}
//将“字符数组x+换行符”写入到“PrintWriter输出流”中,println实际调用的是write函数
publicvoidprintln(charx[]){
synchronized(lock){
print(x);
println();
}
}
//将“字符串x+换行符”写入到“PrintWriter输出流”中,println实际调用的是write函数
publicvoidprintln(Stringx){
synchronized(lock){
print(x);
println();
}
}
//将“对象o对应的字符串+换行符”写入到“PrintWriter输出流”中,println实际调用的是write函数
publicvoidprintln(Objectx){
Strings=String.valueOf(x);
synchronized(lock){
print(s);
println();
}
}
//将“数据args”根据“默认Locale值(区域属性)”按照format格式化,并写入到“PrintWriter输出流”中
publicPrintWriterprintf(Stringformat,Object...args){
returnformat(format,args);
}
//将“数据args”根据“Locale值(区域属性)”按照format格式化,并写入到“PrintWriter输出流”中
publicPrintWriterprintf(Localel,Stringformat,Object...args){
returnformat(l,format,args);
}
//根据“默认的Locale值(区域属性)”来格式化数据
publicPrintWriterformat(Stringformat,Object...args){
try{
synchronized(lock){
ensureOpen();
if((formatter==null)
||(formatter.locale()!=Locale.getDefault()))
formatter=newFormatter(this);
formatter.format(Locale.getDefault(),format,args);
if(autoFlush)
out.flush();
}
}catch(InterruptedIOExceptionx){
Thread.currentThread().interrupt();
}catch(IOExceptionx){
trouble=true;
}
returnthis;
}
//根据“Locale值(区域属性)”来格式化数据
publicPrintWriterformat(Localel,Stringformat,Object...args){
try{
synchronized(lock){
ensureOpen();
if((formatter==null)||(formatter.locale()!=l))
formatter=newFormatter(this,l);
formatter.format(l,format,args);
if(autoFlush)
out.flush();
}
}catch(InterruptedIOExceptionx){
Thread.currentThread().interrupt();
}catch(IOExceptionx){
trouble=true;
}
returnthis;
}
//将“字符序列的全部字符”追加到“PrintWriter输出流中”
publicPrintWriterappend(CharSequencecsq){
if(csq==null)
write("null");
else
write(csq.toString());
returnthis;
}
//将“字符序列从start(包括)到end(不包括)的全部字符”追加到“PrintWriter输出流中”
publicPrintWriterappend(CharSequencecsq,intstart,intend){
CharSequencecs=(csq==null?"null":csq);
write(cs.subSequence(start,end).toString());
returnthis;
}
//将“字符c”追加到“PrintWriter输出流中”
publicPrintWriterappend(charc){
write(c);
returnthis;
}
}
示例代码
关于PrintWriter中API的详细用法,参考示例代码(PrintWriterTest.java):
importjava.io.PrintWriter;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
/**
*PrintWriter的示例程序
*
*
*/
publicclassPrintWriterTest{
publicstaticvoidmain(String[]args){
//下面个函数的作用都是一样:都是将字母“abcde”写入到文件“file.txt”中。
//任选一个执行即可!
testPrintWriterConstrutor();
//testPrintWriterConstrutor();
//testPrintWriterConstrutor();
//测试write(),print(),println(),printf()等接口。
testPrintWriterAPIS();
}
/**
*PrintWriter(OutputStreamout)的测试函数
*
*函数的作用,就是将字母“abcde”写入到文件“file.txt”中
*/
privatestaticvoidtestPrintWriterConstrutor(){
finalchar[]arr={'a','b','c','d','e'};
try{
//创建文件“file.txt”的File对象
Filefile=newFile("file.txt");
//创建文件对应FileOutputStream
PrintWriterout=newPrintWriter(
newFileOutputStream(file));
//将“字节数组arr”全部写入到输出流中
out.write(arr);
//关闭输出流
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*PrintWriter(Filefile)的测试函数
*
*函数的作用,就是将字母“abcde”写入到文件“file.txt”中
*/
privatestaticvoidtestPrintWriterConstrutor(){
finalchar[]arr={'a','b','c','d','e'};
try{
Filefile=newFile("file.txt");
PrintWriterout=newPrintWriter(file);
out.write(arr);
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*PrintWriter(StringfileName)的测试函数
*
*函数的作用,就是将字母“abcde”写入到文件“file.txt”中
*/
privatestaticvoidtestPrintWriterConstrutor(){
finalchar[]arr={'a','b','c','d','e'};
try{
PrintWriterout=newPrintWriter("file.txt");
out.write(arr);
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*测试write(),print(),println(),printf()等接口。
*/
privatestaticvoidtestPrintWriterAPIS(){
finalchar[]arr={'a','b','c','d','e'};
try{
//创建文件对应FileOutputStream
PrintWriterout=newPrintWriter("other.txt");
//将字符串“helloPrintWriter”+回车符,写入到输出流中
out.println("helloPrintWriter");
//将x写入到输出流中
//x对应ASCII码的字母'A',也就是写入字符'A'
out.write(x);
//将字符串""写入到输出流中。
//out.print(x);等价于out.write(String.valueOf(x));
out.print(x);
//将字符'B'追加到输出流中
out.append('B').append("CDEF");
//将"CDEis"+回车写入到输出流中
Stringstr="GHI";
intnum=;
out.printf("%sis%d\n",str,num);
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
运行上面的代码,会在源码所在目录生成两个文件“file.txt”和“other.txt”。
file.txt的内容如下:
abcde
other.txt的内容如下:
helloPrintWriter A65BCDEFGHIis5
以上所述是小编给大家介绍的Java中的PrintWriter知识,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!