欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 学习笔记- File I/O - 文件的读写

程序员文章站 2022-06-01 23:51:47
...

JDK7 中Files类对文件的读写操作大概可以分为:

1. 读取和写入所有字节

 /**
     * Read all bytes from a file.
     * 
     * @param path
     * @return
     * @throws IOException
     */
    public static byte[] readAllBytes(Path path) throws IOException {
        return Files.readAllBytes(path);
    }

    /**
     * Write all bytes to a file.
     * 
     * @param path
     * @param bytes
     * @param option
     * @throws IOException
     */
    public static void writAllBytes(Path path, byte[] bytes, OpenOption option) throws IOException {
        Files.write(path, bytes, option);
    }

 这两个方法要求文件不能够太大,如果文件大小,size > (long)Integer.MAX_VALUE,throw new OutOfMemoryError("Required array size too large");

 

2.读取或写入所有的行。

/**
     * Read all lines from a file.
     * 
     * @param path
     * @param cs
     * @return
     * @throws IOException
     */
    public static List<String> readAllLines(Path path, Charset cs) throws IOException {
        return Files.readAllLines(path, cs);
    }

    /**
     * Write all lines to a file.
     * 
     * @param path
     * @param lines
     * @param cs
     * @param option
     * @throws IOException
     */
    public void writeAllLines(Path path, List<String> lines, Charset cs, OpenOption option) throws IOException {
        Files.write(path, lines, cs, option);
    }

 这两个方法也是一次性操作所有的字节,对于读操作,BufferedReader逐行读取。对于写操作使用BufferedWriter逐行向文件写入。对于大文件这个方法也处理不来。

3.通过Buffered Stream I/O 读写。

 

/**
     * Reading a File by Using Buffered Stream I/O
     * 
     * @param path
     * @param cs
     * @return
     * @throws IOException
     */
    public static List<String> readByBufferedStream(Path path, Charset cs) throws IOException {
        BufferedReader reader = null;
        try {
            reader = Files.newBufferedReader(path, cs);
            String line = null;
            List<String> lines = new ArrayList<String>();
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
            return lines;
        } catch (IOException e) {
            throw (e);
        } finally {
            if (reader != null)
                reader.close();
        }
    }

    /**
     * Writing a File by Using Buffered Stream I/O
     * 
     * @param path
     * @param lines
     * @param cs
     * @param options
     * @throws IOException
     */
    public static void writeByBufferedStream(Path path, List<String> lines, Charset cs, OpenOption options)
            throws IOException {

        BufferedWriter writer = null;
        try {
            writer = Files.newBufferedWriter(path, cs, options);
            for (String line : lines) {
                writer.write(line);
            }
        } catch (IOException e) {
            throw (e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }

 4.通过stream I/O读写文件

  /**
     * Reading a File by Using Stream I/O
     * 
     * @param path
     * @return
     * @throws IOException
     */
    public static List<String> readByStream(Path path) throws IOException {
        List<String> lines = new ArrayList<>();
        InputStream in = null;
        BufferedReader reader = null;
        try {
            in = Files.newInputStream(path, StandardOpenOption.READ);
            reader = new BufferedReader(new InputStreamReader(in));
            String line = null;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            throw (e);
        } finally {
            if (in != null) {
                in.close();
            }
            if (reader != null) {
                reader.close();
            }
        }
        return lines;
    }

    /**
     * Write to a file by Stream I/O
     * 
     * @param lines
     * @param path
     * @param options
     * @param cs
     * @throws IOException
     */
    public static void writeByStream(List<String> lines, Path path, Charset cs, OpenOption... options)
            throws IOException {
        OutputStream out = null;
        try {
            out = new BufferedOutputStream(Files.newOutputStream(path, options));
            for (String line : lines) {
                out.write(line.getBytes(cs), 0, line.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null)
                out.close();
        }
    }

 5.通过Channel I/O读写文件

 /**
     * Read or write by Using Channel I/O
     * 
     * @param path
     * @param options
     * @throws IOException
     */
    public static void readAndWriteByChannel(Path readPath, Path writePath) throws IOException {

        ByteChannel rbc = null;
        ByteChannel wbc = null;
        try {
            if (!Files.exists(writePath, LinkOption.NOFOLLOW_LINKS)) {
                Files.createFile(writePath);
            }
            rbc = Files.newByteChannel(readPath, StandardOpenOption.READ);
            wbc = Files.newByteChannel(writePath, StandardOpenOption.APPEND);
            ByteBuffer buf = ByteBuffer.allocate(10);
            String encoding = System.getProperty("file.encoding");
            while (rbc.read(buf) > 0) {
                System.out.println("before rewind:\n" + buf);
                buf.rewind();
                System.out.println("after rewind:\n" + buf);
                CharBuffer cb = Charset.forName(encoding).decode(buf);
                buf.rewind();
                wbc.write(buf);
                System.out.println(cb);
                System.out.println("before flip:\n" + buf);
                buf.flip();
                System.out.println("after flip:\n" + buf);
            }

        } catch (IOException e) {
            System.out.println("caught exception: " + e);
            e.printStackTrace();
        } finally {
            if (rbc != null) {
                rbc.close();
            }
            if (wbc != null) {
                rbc.close();
            }
        }
    }