打印流
打印流
打印流根据流的分类:
l 字节打印流 PrintStream
l 字符打印流 PrintWriter
/*
* 需求:把指定的数据,写入到printFile.txt文件中
*
* 分析:
* 1,创建流
* 2,写数据
* 3,关闭流
*/
public class PrintWriterDemo {
public static void main(String[] args) throws IOException {
//创建流
//PrintWriter out = new PrintWriter(new FileWriter("printFile.txt"));
PrintWriter out = new PrintWriter("printFile.txt");
//2,写数据
for (int i=0; i<5; i++) {
out.println("helloWorld");
}
//3,关闭流
out.close();
}
}
打印流完成数据自动刷新
可以通过构造方法,完成文件数据的自动刷新功能
l 构造方法:
l 开启文件自动刷新写入功能
public PrintWriter(OutputStream out, boolean autoFlush)
public PrintWriter(Writer out, boolean autoFlush)
/*
* 分析:
* 1,创建流
* 2,写数据
*/
public class PrintWriterDemo2 {
public static void main(String[] args) throws IOException {
//创建流
PrintWriter out = new PrintWriter(new FileWriter("printFile.txt"), true);
//2,写数据
for (int i=0; i<5; i++) {
out.println("helloWorld");
}
//3,关闭流
out.close();
}
}
复制文件
public class Demo02 {
public static void main(String[] args) throws IOException {
//文件复制
FileReader fr=new FileReader("D:\\io0512\\print.txt");
//添加缓冲流
BufferedReader br=new BufferedReader(fr);
//明确目的地
FileWriter fw=new FileWriter("D:\\io0512\\a\\print.txt");//续写加true
//添加打印流
PrintWriter pw=new PrintWriter(fw,true);//开启文件自动刷新写入功能
//开始复制
String len=null;
while((len=br.readLine())!=null){
pw.println(len);
}
br.close();
pw.close();
}
}


浙公网安备 33010602011771号