Java多种写文件方式

写文件在开发小工具时经常使用到,好比爬取某些网站的信息,数据量不是很大,保存到本地便可。固然若是会一些额外的技能,好比多线程,网络之类的,小工具会更加有意思。java

这里看下Java不一样的写文件方式:数组

  • BufferedWriter
  • PrintWriter
  • FileOutputStream
  • DataOutputStream
  • RandomAccessFile
  • FileChannel
  • Files

BufferedWriter

把类中定义的方法信息,写入文件bash

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();
    }
复制代码

image-20190326081928256

追加信息到已经存在的文件:网络

static void appendFileWithBufferedWriter() throws IOException {
    	// FileWriter的第二个参数表明是否追加
        BufferedWriter writer = new BufferedWriter(new FileWriter(fileName,true));
        writer.append("追加信息");
        writer.close();
    }
复制代码

image-20190326082146211

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();
    }
复制代码

image-20190326082536781

FileOutputStream

用来写入二进制数据到文件中,须要将String转换为bytes。app

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();
    }
复制代码

image-20190326083040667

DataOutputStream

写法如上dom

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();
    }
复制代码

image-20190326084711766

FileChannel

在处理大文件的时候,FileChannel会比标准的io更快。ui

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();

}
复制代码

image-20190326085329071

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));
    }
复制代码

image-20190326085644551

最后

操做文件的时候记得要关闭文件流,也能够使用java7的try-with-resource语法。

  • BufferedWriter 提供高效的读写字符,字符串,数组。
  • PrintWriter 写入格式化文字
  • FileOutputStream 写入二进制流
  • DataOutputStream 写primary类型
  • RandomAccessFile 随机读写文件,在指定的位置编辑文件
  • FileChannel 写入大文件

参考

相关文章
相关标签/搜索