您的位置 首页 java

java字符输出流PrintWriter

/**

* 测试字符输出流PrintWriter

*/

public class TestPrintWriter {

public static void main(String[] args) {

try (BufferedReader br = new BufferedReader(new File Reader(“iostream/testFile5.txt”));

PrintWriter pw = new PrintWriter(“iostream/testFile6.txt”)){

//PrintWriter为节点流,在实例化pw时生成了BufferedWriter(OutputStreamWriter(FileOutputStream(String fileName)))对象,实际依然使用了字节流转字符流

for (String line = br.readLine();line!=null;line = br.readLine()){

pw.println(line);

//使用PrintWriter拷贝字符串,.println()方法类似System.out.println,对每一行内容输出之后不需要手动newLine换行

}

pw.flush();

//PrintWriter作为节点流时需要手动flush

}catch ( Exception e){

e.printStackTrace();

}

try(BufferedReader br = new BufferedReader(new FileReader(“iostream/testFile6.txt”));

PrintWriter pw = new PrintWriter(new FileOutputStream(“iostream/testFile7.txt”),true)){

//PrintWriter作为处理流使用,将 FileOutputStream 对象传入构造器,实例化pw时会外套BufferedWriter(OutputStreamWriter,将参数autoFlush设为true,每次println会自动flush

for (String line = br.readLine();line!=null;line = br.readLine()){

pw.println(line);

}

//无需flush,PrintWriter没有缓冲,需要实例Buffered使用,如果构造器直接传入Writer: new PrintWriter(new FileWriter(“xxx”))这种情况不会外套BufferedWriter

}catch (Exception e){

e.printStackTrace();

}

}

}

文章来源:智云一二三科技

文章标题:java字符输出流PrintWriter

文章地址:https://www.zhihuclub.com/178562.shtml

关于作者: 智云科技

热门文章

网站地图