java中PrintWriter打印流简介说明
下文笔者讲述java中PrintWriter打印流的简介说明,如下所示
PrintWriter字符打印流
1.可以打印各种数据类型 2.封装了字符输出流,还可以做字符流和字节流的转换 3.可以使用自动刷新。 只有在调用println、printf或者format的其中一个方法时才可能完成此操作。 4.可以直接向文件中写数据
使用字符打印流向文件中写入数据
public class PrintDemo {
public static void main(String[] args) {
PrintWriter pw = null;
try {
//创建字符打印流对象
pw = new PrintWriter("java265.txt");
//向文件中分别打印boolean、字符、int、字符串
pw.print(true);
pw.print('java265');
pw.print(888);
pw.print("猫猫");
//刷新
pw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
//字符打印流也是需要关闭的,但是不用处理异常
if(pw != null)
pw.close();
}
}
}
从文件中读取数据并且打印在控制台
public class PrintDemo2 {
public static void main(String[] args) {
BufferedReader br = null;
PrintWriter pw = null;
try {
//创建高效缓冲区字符输入流对象
br = new BufferedReader(new FileReader("java265.txt"));
//创建打印流对象
//pw = new PrintWriter(System.out);
//设置自动刷新的打印流在文件对象后面加true
pw = new PrintWriter(System.out,true);
String line = null;
while((line = br.readLine()) != null) {
pw.println(line);
//当使用自动刷新构造器时就不需要手动刷新
//pw.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(br != null)
br.close();
if(pw != null)
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
使用打印流来复制文本文件
public class PrintDemo3 {
public static void main(String[] args) {
BufferedReader br = null;
PrintWriter pw = null;
try {
//创建高效缓冲区字符输入流对象
br = new BufferedReader(new FileReader("java265.txt"));
//创建打印流对象
//pw = new PrintWriter(System.out);
//设置自动刷新的打印流在文件对象后面加true
pw = new PrintWriter(new FileWriter("Student1.txt"));
String line = null;
while((line = br.readLine()) != null) {
pw.println(line);
//当使用自动刷新构造器时就不需要手动刷新
//pw.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(br != null)
br.close();
if(pw != null)
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


