Java写文件

来源:互联网 发布:多功能水枪 基本数据 编辑:程序博客网 时间:2024/06/07 06:02

Java写文件有三种常用的方式,分别是用FileOutputStream、BufferedOutputStream和FileWriter
其中,FileWriter的执行速度最快,BufferedOutputStream次之,FileOutputStream最慢
三种方法的实现方式如下:

FileOutputStream fileOutputStream = null;try{    fileOutputStream = new FileOutputStream(new File("..."));    fileOutputStream.write("xavier".getByte());    fileOutputStream.close();} catch (final IOException e) {    pass;} finally {    if (fileOutputStream != null)        try {            fileOutputStream.close();        } catch (final IOException e){            e.printStackTrace();        }}
FileOutputStream fileOutputStream = null;BufferedOutputStream bufferedOutputStream = null;try{    fileOutputStream = new FileOutputStream(new File("..."));    bufferedOutputStream = new BufferedOutputStream(fileOutputStream);    bufferedOutputStream .write("xavier".getByte());    bufferedOutputStream.flush();    fileOutputStream.close();    bufferedOutputStream.close;} catch (final IOException e) {    pass;} finally {    try {        if (fileOutputStream != null)            fileOutputStream.close();        if (bufferedOutputStream!= null)            bufferedOutputStream.close();    } catch (final IOException e){        e.printStackTrace();    }}
FileWriter fileWriter = null;try{    fileWriter = new FileWriter (new File("..."));    fileWriter.write("xavier");    fileWriter .close();} catch (final IOException e) {    pass;} finally {    if (fileWriter != null)        try {            fileWriter .close();        } catch (final IOException e){            e.printStackTrace();        }}

如上述,三种方法,论性价比而言,肯定是FileWriter最好用,不仅速度快,而且写起来也方便,更加不需要将String类型转换为Byte进行传入

但是FileWriter有一个缺点,他会使用系统默认的编码方式进行文件写入,而我们无法更改;而当我们使用FileOutputStream或BufferedOutputStream时,当转换String为Byte类型时,可以使用String.getByte(charsetName)方法转换编码方式。

最容易出bug的就是在Windows下使用FileWriter,写入文件时保存的GBK编码,而很多时候,GBK编码会出现乱码,所以最好的解决方案是用BufferedOutputStream,在将String转换为Byte时使用getByte(“utf-8”),这样子不仅不会出现乱码的问题,写入的速度也不会比FileWriter慢多少。

0 0
原创粉丝点击