1.java.io.PrintWriter是java中很常见的一个类,该类可用来创建一个文件并向文本文件写入数据。可以理解为java中的文件输出,java中的文件输入则是java.io.File。
2.常用的构造方法:
提供了很多构造方法,包括直接对文件写操作的
-
PrintWriter(String fileName)
-
PrintWriter(File file)
以上两种构造方法都是按照系统默认字符集对指定文件进行写操作的
- PrintWriter(String fileName,String csn)
- PrintWriter(File file,String csn)
以上两种则是按照指定的字符集写操作,csn是charset name 字符集名称
注:java.io.PrintWriter的构造方法并不局限于一下范例,java.io.PrintWriter构造方法的参数也可以是字节流, 即:
PrintWriter的构造方法如果第一个参数为流,那么就可以再传入一个boolean型的参数,若该值为true,那么当前PrintWriter就具有了自动行刷新功能,这时每当我们使用println方法写出一行字符串后就会自动调用flush().
- 注意:print方法是不会自动刷新的!因为本篇文章主要讲关于文件的操作,所以参数是字节流的java.io.PrintWriter就不讲了。
(1)构造方法参数为String类型的对象,值应为文件全路径。若文件不存在,则会先创建文件。
public PrintWriter(String fileName) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
false);
}
举例:若aaa.txt不存在,则先创建aaa.txt,再向aaa.txt中写入“Hello World”。若aaa.txt存在,则直接向aaa.txt中写入“Hello World”(每次写入的内容都会覆盖原来的内容)。
public class FileTest {
public static void main(String[] args) {
PrintWriter pw = null;
try {
pw = new PrintWriter("f://aaa.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.print("Hello World");
pw.close();
}
}
(2)构造方法参数为File类型的对象,值应为File。
public PrintWriter(File file) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
false);
}
举例:
public class FileTest {
public static void main(String[] args) {
File file = new File("f://ccc.txt");
System.out.println(file.exists());//输出为false,因为本地没有ccc.txt
PrintWriter pw = null;
try {
pw = new PrintWriter(file);//先创建ccc.txt(若存在,则不会创建)
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.print("Hello World");
pw.close();
}
}
3.其方法可以去查API,此处只列出几个常见的方法:
(1)print(String str):向文件写入一个字符串。
(2)print(char[] ch):向文件写入一个字符数组。
(3)print(char c):向文件写入一个字符。
(4)print(int i):向文件写入一个int型值。
(5)print(long l):向文件写入一个long型值。
(6)print(float f):向文件写入一个float型值。
(7)print(double d):向文件写入一个double型值。
(8)print(boolean b):向文件写入一个boolean型值。