Java 文件


写文件、读文件的所有内容

下面是读文件所有内容的例子:

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class ReadFile {
    public static void main(String[] args) {
        try {
            // 读取文件的所有字节
            Path file = Paths.get("a2.txt");
            byte[] buf = new byte[] { 0x61, (byte) 0xe4, (byte) 0xba, (byte) 0x8c };
            Files.write(file, buf);

            byte[] fileContent = Files.readAllBytes(file);
            for (byte b : fileContent)
                System.out.println(Integer.toHexString(b & 0x000000ff) );
                    // 61 e4 ba 8c

            // 读取文件的所有行
            Charset charset = Charset.forName("utf-8");
            List<String> lines = Files.readAllLines(file, charset);
            for (String str : lines)
                System.out.println("\t" + str);    // a二
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


使用缓冲流读写文件

下面是使用缓冲流读写文件的例子:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class BufferedRead {
    public static void main(String[] args) {
        Path file = Paths.get("a2.txt");
        Charset charset = Charset.forName("utf-8");

        String str = "a中";
        try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
            writer.write(str, 0, str.length());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 读取文件的所有行
        try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);    // a中
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用Channel读写文件

流输入输出每次读取一个字符,Channel每次读取一个缓存区。

下面是使用Channel读写文件的例子:

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ChannelRead {
    public static void main(String[] args) {
        Path file = Paths.get("a2.txt");
        Charset charset = Charset.forName("utf-8");

        String str = "a中";
        try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
            writer.write(str, 0, str.length());
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (SeekableByteChannel c = Files.newByteChannel(file)) {
            ByteBuffer buf = ByteBuffer.allocate(4);

            while (c.read(buf) > 0) {
                buf.rewind();
                System.out.print(charset.decode(buf));    // a中
                buf.flip();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

任意访问文件

读写一个文件的任意位置的内容。

下面是任意访问文件的例子:

import java.io.IOException;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class RandomRead {
    public static void main(String[] args) throws Exception {
        if (!new File("a.txt").exists())
            new File("a.txt").createNewFile();

        Path file = Paths.get("a.txt");

        try (FileChannel fc = (FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE,
                StandardOpenOption.TRUNCATE_EXISTING))) {
            // 写a..z
            String str = "abcdefghijklmnopqrstuvwxyz";
            byte data[] = str.getBytes();
            ByteBuffer out = ByteBuffer.wrap(data);

            fc.position(0);
            while (out.hasRemaining())
                fc.write(out);

            // 写0123456
            String str2 = "0123456";
            byte data2[] = str2.getBytes();
            ByteBuffer out2 = ByteBuffer.wrap(data2);

            fc.position(7);
            while (out2.hasRemaining())
                fc.write(out2);

            // 读文件内容
            ByteBuffer in = ByteBuffer.allocate(26);
            int nread;
            fc.position(0);
            do {
                nread = fc.read(in);
            } while (nread != -1 && in.hasRemaining());

            String fileContent = new String(in.array());
            System.out.println(fileContent);    // abcdefg0123456opqrstuvwxyz
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}