PrintWriter,FileWriter学习

257 阅读2分钟

PrintWriter

概念

具有自动行刷新的缓冲字符输出流,特点是可以按行写出字符串,并且可以自动行刷新。

用法:

例子:

复制文件

public class PrintWriterTest {
    public static void main(String[] args) throws IOException {
        //创建数据源对象,读取文件test.txt
        FileReader is = new FileReader("test.txt");
        //BufferedReader提供通用的缓冲方式文本读取,而且提供了很实用的readLine,读取一个文本行,从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取。
        BufferedReader br = new BufferedReader(is);

        //创建目标路径对象
        PrintWriter os = new PrintWriter(new FileWriter("d.txt"), true);

        //复制文件
        String line;  //交换数的中介
        while ((line = br.readLine()) != null) {
            os.println(line);
        }

        //释放资源
        is.close();
        os.close();
    }
}

例子2:往b.txt里面写入数据,然后复制到c.txt里面去

public static void main(String[] args) throws IOException {
        //创建打印流
        PrintWriter print = new PrintWriter("b.txt");

        //输出数据到b.txt
        //PrintWriter类的println(String x)方法和writer(Stirng x)方法都表示把输入写到输出流中
        print.write("hello");
        print.write("world");
        print.write("!");

        //使用打印流特有方法输出println()
        //与平台无关
        print.println("hello");
        print.println("world");
        print.println("!");

        //创建一个新的对象,此对对象具有自动刷新的功能,即在释放资源之前就写入数据
        PrintWriter out = new PrintWriter(new FileWriter("c.txt"), true);

        //输出数据
        out.println("hello");
        out.println("world");
        out.println("!");

        //释放资源
        print.close();
        out.close();

    }

FileWriter

FileWriter:是用来方便的将字符数据写入文件的类

FileWriter的用法就三个字:**创,写,关

创:new 一个

写:利用 wirter() 方法

关:利用 close() 方法

*下面就是创建一个文件的具体步骤:*

public class FileWriter01 {
	public static void main(String[] args) throws IOException {
		FileWriter fw = new FileWriter("file01.txt");
		fw.write("Hello world");

		fw.close();
	}
}

如果这个文件不存在,那么就会帮我们自动创建一个。

如果这个纯文本文件已经存在,并且里面有内容,此时我们再添加内容,就会覆盖掉这个纯文本文件已有的内容。

不想覆盖,创建对象的时候我们这样创建:

FileWriter fw = new FileWriter("file01.txt",true);

当我们调用 write() 方法的时候,我们写进去的,Windows 的记事本会翻译它,翻译成二进制,翻译成能够被计算机识别的语言。翻译总得有个标准,首先就会先找 ASCII 码表上的内容,如果没有呢?就会再去找万国码的 Unicode 表来进行翻译。我们在调用 write() 的时候,也可以写个 20013 试试,这是中国的 '中' 字。**

为了方便需要我们需要记住在 ASCII 码表中常用的:48 - 0,65 - A,97 - a

public class FileWriter01 {
public static void main(String[] args) throws IOException {
    FileWriter fw = new FileWriter("file01.txt");
		fw.write(48);
		fw.write(65);
		fw.write(97);
    fw.write(20013);
		fw.close();
	}

}
显示出来的结果:0Aa中