方法 3:PrintWriter
PrintWriter 也属于字符流体系中的一员,它虽然叫“字符打印流”,但使用它也可以实现文件的写入,实现代码如下:
/** * 方法 3:使用 PrintWriter 写文件 * @param filepath 文件目录 * @param content 待写入内容 * @throws IOException */ public static void printWriterMethod(String filepath, String content) throws IOException { try (PrintWriter printWriter = new PrintWriter(new FileWriter(filepath))) { printWriter.print(content); } }
从上述代码可以看出,无论是 PrintWriter 还是 BufferedWriter 都必须基于 FileWriter 类来完成调用。
方法 4:FileOutputStream
上面 3 个示例是关于字符流写入文件的一些操作,而接下来我们将使用字节流来完成文件写入。我们将使用 String 自带的 getBytes() 方法先将字符串转换成二进制文件,然后再进行文件写入,它的实现代码如下:
/** * 方法 4:使用 FileOutputStream 写文件 * @param filepath 文件目录 * @param content 待写入内容 * @throws IOException */ public static void fileOutputStreamMethod(String filepath, String content) throws IOException { try (FileOutputStream fileOutputStream = new FileOutputStream(filepath)) { byte[] bytes = content.getBytes(); fileOutputStream.write(bytes); } }
方法 5:BufferedOutputStream
BufferedOutputStream 属于字节流体系中的一员,与 FileOutputStream 不同的是,它自带了缓冲区的功能,因此性能更好,它的实现代码如下:
/** * 方法 5:使用 BufferedOutputStream 写文件 * @param filepath 文件目录 * @param content 待写入内容 * @throws IOException */ public static void bufferedOutputStreamMethod(String filepath, String content) throws IOException { try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream( new FileOutputStream(filepath))) { bufferedOutputStream.write(content.getBytes()); } }