PrintWriter类详解

1.java.io.PrintWriter是java中很常见的一个类,该类可用来创建一个文件并向文本文件写入数据。可以理解为java中的文件输出,java中的文件输入则是java.io.File。

2.常用的构造方法:

注:java.io.PrintWriter的构造方法并不局限于一下范例,java.io.PrintWriter构造方法的参数也可以是字节流。因为本篇文章主要讲关于文件的操作,所以参数是字节流的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.常用方法:

(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型值。

猜你喜欢

转载自blog.csdn.net/Dream_Ryoma/article/details/80873718