您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
javase第三季学习笔记-IO之打印流
发布时间:2017-08-10 14:56:47编辑:雪饮阅读()
打印流概述
打印流的主要功能是用于输出,在整个IO包中打印流分为两种类型:
字节打印流:PrintStream
字符打印流:PrintWriter
打印流可以很方便的进行输出
示例代码:使用PrintStream打印流,将信息打印于文件中,字节打印流
package com.vince.print;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
public class PrintStreamDemo {
//使用PrintStream打印流
public static void print(){
String filePath="E:"+File.separator+"duminjie_love_gaojiupan"+File.separator+"BaiduNetdiskDownload.txt";
try {
OutputStream out = new FileOutputStream(filePath);
BufferedOutputStream bos=new BufferedOutputStream(out);
//构造字节打印流对象
PrintStream ps=new PrintStream(bos);
ps.println(3.14f);
ps.println(188);
ps.println(true);
ps.println("得意之时谨记,一半命运还掌握在上帝手里;失意之时须知,一半命运还掌握在自己手里。");
ps.flush();
//关闭流
out.close();
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
public static void main(String[] args) {
print();
}
}
PrintStream
public class PrintStream
extends FilterOutputStream
implements Appendable,Closeable
PrintStream为其它输出流添加了功能,使它们能够方便的打印各种数据值的表示形式。
它还提供其它两项功能。与其它输出流不同,PrintStream永远不会抛出IOException;而是,异常情况仅设置可通过checkError方法测试的内部标志。另外,为了自动刷新,可以创建一个PrintStream;这意味着可在写入byte数组之后自动调用flush方法,可调用其中一个println方法,或写入一个换行符或字节(’\n’)
示例代码:使用PrintWriter将信息打印于文件中,字符打印流
package com.vince.print;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class PrintStreamDemo {
public static void print(){
String filePath="E:"+File.separator+"duminjie_love_gaojiupan"+File.separator+"BaiduNetdiskDownload.txt";
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
PrintWriter pw=new PrintWriter(bw);
pw.print("\r\n");
pw.println(105);
pw.println("文死谏,武死战,百无一用是书生,临危一死报君王");
pw.flush();
pw.close();
bw.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
public static void main(String[] args) {
print();
}
}
关键字词:javase,io,打印流