写文件在开发小工具时常用到, 比如爬取某些网站的信息, 数据量不是很大, 保存到本地即可. 当然如果会一些额外的技能, 比如多线程, 网络之类的, 小工具会更加有意思.
这里看下 Java 不同的写文件方式:
- BufferedWriter
- PrintWriter
- FileOutputStream
- DataOutputStream
- RandomAccessFile
- FileChannel
- Files
- BufferedWriter
把类中定义的方法信息, 写入文件
- static String fileName = "/Users/aihe/tmp/writeFileDemo.txt";
- static void writeFileWithBufferedWriter() throws IOException {
- Method[] methods = WriteFileDemo.class.getDeclaredMethods();
- String str = Arrays.toString(methods);
- BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
- writer.write(str);
- writer.close();
- }
追加信息到已经存在的文件:
- static void appendFileWithBufferedWriter() throws IOException {
- // FileWriter 的第二个参数代表是否追加
- BufferedWriter writer = new BufferedWriter(new FileWriter(fileName,true));
- writer.append("追加信息");
- writer.close();
- }
PrintWriter
PrintWriter 可以输出格式化的信息到文件中.
- static void writingFileWithPrintWriter()
- throws IOException {
- Method[] methods = WriteFileDemo.class.getDeclaredMethods();
- String str = Arrays.toString(methods);
- // 可以使用 FileWriter,BufferedWriter
- FileWriter fileWriter = new FileWriter(fileName);
- PrintWriter printWriter = new PrintWriter(fileWriter);
- printWriter.printf("当前类的方法信息: %s \n 方法的个数:%d \n", str, methods.length);
- printWriter.close();
- }
FileOutputStream
用来写入二进制数据到文件中, 需要将 String 转换为 bytes.
- static void writingFileWithFileOutputStream()
- throws IOException {
- Method[] methods = WriteFileDemo.class.getDeclaredMethods();
- String str = Arrays.toString(methods);
- FileOutputStream outputStream = new FileOutputStream(fileName);
- // 需要将 String 转换为 bytes
- byte[] strToBytes = str.getBytes();
- outputStream.write(strToBytes);
- outputStream.close();
- }
DataOutputStream
写法如上
- static void writingFileWithDataOutputStream()
- throws IOException {
- Method[] methods = WriteFileDemo.class.getDeclaredMethods();
- String str = Arrays.toString(methods);
- FileOutputStream fos = new FileOutputStream(fileName);
- DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
- outStream.writeUTF(str);
- outStream.close();
- // verify the results
- String result;
- FileInputStream fis = new FileInputStream(fileName);
- DataInputStream reader = new DataInputStream(fis);
- result = reader.readUTF();
- reader.close();
- System.out.println(result.equals(str));
- }
RandomAccessFile
想要写入或者编辑一个已经存在的文件, 而不是写入一个全新的文件或者单纯的追加, 那么我们可以使用 RandomAccessFile. 这个类可以让我们写入特定的位置, 如下:
写入中文的时候使用 writeUTF 方法, 不然可能会乱码
- static void writeToPositionWithRAF(String filename, long position)
- throws IOException {
- RandomAccessFile writer = new RandomAccessFile(filename, "rw");
- writer.seek(position);
- // 写入中文的时候防止乱码
- writer.writeUTF("新内容");
- writer.close();
- }
FileChannel
在处理大文件的时候, FileChannel 会比标准的 io 更快.
- static void writeWithFileChannel() throws IOException {
- RandomAccessFile stream = new RandomAccessFile(fileName, "rw");
- FileChannel channel = stream.getChannel();
- String value = WriteFileDemo.class.getSimpleName();
- byte[] strBytes = value.getBytes();
- ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
- buffer.put(strBytes);
- buffer.flip();
- channel.write(buffer);
- stream.close();
- channel.close();
- }
Files
Files 是 Java7 引入的工具类, 通过它, 我们可以创建, 移动, 删除, 复制文件. 目录也是一种特殊的文件, 对目录也适用. 当然也可以用于读写文件
- static void writeWithFiles()
- throws IOException {
- String str = "Hello";
- Path path = Paths.get(fileName);
- byte[] strToBytes = str.getBytes();
- Files.write(path, strToBytes);
- String read = Files.readAllLines(path).get(0);
- System.out.println(str.equals(read));
- }
最后
操作文件的时候记得要关闭文件流, 也可以使用 java7 的 try-with-resource 语法.
BufferedWriter 提供高效的读写字符, 字符串, 数组.
PrintWriter 写入格式化文字
FileOutputStream 写入二进制流
DataOutputStream 写 primary 类型
RandomAccessFile 随机读写文件, 在指定的位置编辑文件
FileChannel 写入大文件
参考
Java - Write to File https://www.baeldung.com/java-write-to-file
来源: https://juejin.im/post/5c997a29f265da611846b83d