蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Java 8 NIO Files 临时目录读写、复制移动、walk/find、属性视图与流通道实测

JAVAWindows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。ExploreNioFile.java
ExploreNioFile.java335 行
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.FileStore;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.nio.file.attribute.UserPrincipal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ExploreNioFile {
    private static void deleteRecursively(Path root) throws IOException {
        if (root == null || !Files.exists(root)) return;
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.deleteIfExists(file);
                return FileVisitResult.CONTINUE;
            }
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.deleteIfExists(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }

    private static String escapeJson(String s) {
        StringBuilder sb = new StringBuilder("\"");
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '"': sb.append("\\\""); break;
                case '\\': sb.append("\\\\"); break;
                case '\n': sb.append("\\n"); break;
                case '\r': sb.append("\\r"); break;
                case '\t': sb.append("\\t"); break;
                default:
                    if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
                    else sb.append(c);
            }
        }
        return sb.append('"').toString();
    }

    private static String toJson(Object obj) {
        if (obj == null) return "null";
        if (obj instanceof Boolean || obj instanceof Number) return obj.toString();
        if (obj instanceof String) return escapeJson((String) obj);
        if (obj instanceof List<?>) {
            StringBuilder sb = new StringBuilder("[");
            List<?> list = (List<?>) obj;
            for (int i = 0; i < list.size(); i++) {
                if (i > 0) sb.append(", ");
                sb.append(toJson(list.get(i)));
            }
            return sb.append("]").toString();
        }
        if (obj instanceof Map<?, ?>) {
            StringBuilder sb = new StringBuilder("{");
            boolean first = true;
            for (Map.Entry<?, ?> e : ((Map<?, ?>) obj).entrySet()) {
                if (!first) sb.append(", ");
                first = false;
                sb.append(escapeJson(String.valueOf(e.getKey()))).append(": ").append(toJson(e.getValue()));
            }
            return sb.append("}").toString();
        }
        return escapeJson(String.valueOf(obj));
    }

    private static Map<String, Object> makeCase(String name, String summary, Object expected, Object actual) {
        Map<String, Object> c = new LinkedHashMap<String, Object>();
        c.put("name", name);
        c.put("summary", summary);
        c.put("expected", expected);
        c.put("actual", actual);
        c.put("passed", expected.equals(actual));
        return c;
    }

    public static void main(String[] args) throws Exception {
        List<Map<String, Object>> cases = new ArrayList<Map<String, Object>>();
        Path workspace = Files.createTempDirectory("java-nio-files-lab-");
        try {
            // Case 1: File content read/write, append, copy, move, delete, deleteIfExists, exception handling
            {
                Path f1 = workspace.resolve("note.txt");
                Files.write(f1, Arrays.asList("line1", "line2"), StandardCharsets.UTF_8);
                Files.write(f1, "line3\n".getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);

                List<String> allLinesDefault = Files.readAllLines(f1, StandardCharsets.UTF_8);
                byte[] allBytes = Files.readAllBytes(f1);
                List<String> streamLines;
                try (Stream<String> st = Files.lines(f1, StandardCharsets.UTF_8)) {
                    streamLines = st.collect(Collectors.toList());
                }

                Path copied = workspace.resolve("note-copy.txt");
                Files.copy(f1, copied, StandardCopyOption.REPLACE_EXISTING);
                Path moved = workspace.resolve("note-moved.txt");
                Files.move(copied, moved, StandardCopyOption.REPLACE_EXISTING);

                boolean copyGone = !Files.exists(copied);
                boolean movedExists = Files.exists(moved);
                Files.delete(moved);
                boolean deleteSecondIfExists = Files.deleteIfExists(moved);

                boolean noSuchThrown = false;
                try {
                    Files.delete(workspace.resolve("missing.txt"));
                } catch (NoSuchFileException ex) {
                    noSuchThrown = true;
                }

                Map<String, Object> expected = new LinkedHashMap<String, Object>();
                expected.put("lines", Arrays.asList("line1", "line2", "line3"));
                expected.put("stream_equals_readalllines", true);
                expected.put("bytes_nonempty", true);
                expected.put("copy_then_move_ok", true);
                expected.put("delete_if_exists_missing", false);
                expected.put("delete_missing_throws_nsfe", true);

                Map<String, Object> actual = new LinkedHashMap<String, Object>();
                actual.put("lines", allLinesDefault);
                actual.put("stream_equals_readalllines", streamLines.equals(allLinesDefault));
                actual.put("bytes_nonempty", allBytes.length > 10);
                actual.put("copy_then_move_ok", copyGone && movedExists);
                actual.put("delete_if_exists_missing", deleteSecondIfExists);
                actual.put("delete_missing_throws_nsfe", noSuchThrown);

                cases.add(makeCase(
                    "nio_file_rw_copy_move_delete",
                    "验证 Files 的 write/APPEND、readAllBytes/readAllLines/lines、copy/move/delete/deleteIfExists 及 NoSuchFileException",
                    expected,
                    actual
                ));
            }

            // Case 2: Directories (createDirectory, createDirectories, list, newDirectoryStream, walk, find)
            {
                Path singleDir = Files.createDirectory(workspace.resolve("single"));
                Path nestedDir = Files.createDirectories(workspace.resolve("tree/a/b"));
                Path txt1 = Files.createFile(workspace.resolve("tree/root.txt"));
                Path txt2 = Files.createFile(nestedDir.resolve("deep.txt"));
                Path log1 = Files.createFile(nestedDir.resolve("ignore.log"));

                List<String> topEntries;
                try (Stream<Path> s = Files.list(workspace.resolve("tree"))) {
                    topEntries = s.map(p -> p.getFileName().toString()).sorted().collect(Collectors.toList());
                }

                List<String> dsEntries = new ArrayList<String>();
                try (DirectoryStream<Path> ds = Files.newDirectoryStream(nestedDir)) {
                    for (Path p : ds) {
                        dsEntries.add(p.getFileName().toString());
                    }
                }
                Collections.sort(dsEntries);

                long walkCount;
                try (Stream<Path> s = Files.walk(workspace.resolve("tree"))) {
                    walkCount = s.count();
                }

                List<String> foundTxt;
                try (Stream<Path> s = Files.find(
                        workspace.resolve("tree"),
                        Integer.MAX_VALUE,
                        (p, attrs) -> attrs.isRegularFile() && p.toString().endsWith(".txt"))) {
                    foundTxt = s.map(p -> p.getFileName().toString()).sorted().collect(Collectors.toList());
                }

                Map<String, Object> expected = new LinkedHashMap<String, Object>();
                expected.put("single_is_dir", true);
                expected.put("top_list", Arrays.asList("a", "root.txt"));
                expected.put("directory_stream_nested", Arrays.asList("deep.txt", "ignore.log"));
                expected.put("walk_total_nodes", 6);
                expected.put("found_txt_files", Arrays.asList("deep.txt", "root.txt"));

                Map<String, Object> actual = new LinkedHashMap<String, Object>();
                actual.put("single_is_dir", Files.isDirectory(singleDir));
                actual.put("top_list", topEntries);
                actual.put("directory_stream_nested", dsEntries);
                actual.put("walk_total_nodes", (int) walkCount);
                actual.put("found_txt_files", foundTxt);

                // silence unused variable warnings while keeping explicit creation
                if (!Files.exists(txt1) || !Files.exists(txt2) || !Files.exists(log1)) {
                    throw new AssertionError("Created files missing");
                }

                cases.add(makeCase(
                    "nio_directory_walk_and_find",
                    "验证 createDirectory/createDirectories/createFile、list、newDirectoryStream、walk 与 find 递归筛选",
                    expected,
                    actual
                ));
            }

            // Case 3: Attributes, setLastModifiedTime, PosixFilePermissions parsing, owner, FileStore, probeContentType
            {
                Path attrFile = workspace.resolve("attr.txt");
                Files.write(attrFile, "hello-nio".getBytes(StandardCharsets.UTF_8));
                FileTime targetTime = FileTime.fromMillis(1700000000000L);
                Files.setLastModifiedTime(attrFile, targetTime);
                FileTime observedTime = Files.getLastModifiedTime(attrFile);

                Set<PosixFilePermission> parsedPerms = PosixFilePermissions.fromString("rwxr-x---");
                UserPrincipal owner = Files.getOwner(attrFile);
                FileStore store = Files.getFileStore(attrFile);
                String mime = Files.probeContentType(attrFile);

                Map<String, Object> expected = new LinkedHashMap<String, Object>();
                expected.put("exists_regular_rw", Arrays.asList(true, true, true, true));
                expected.put("size_bytes", 9);
                expected.put("modified_time_millis", 1700000000000L);
                expected.put("posix_perm_count", 5);
                expected.put("owner_nonempty", true);
                expected.put("store_nonnull", true);
                expected.put("probe_content_type_ok", true);

                Map<String, Object> actual = new LinkedHashMap<String, Object>();
                actual.put("exists_regular_rw", Arrays.asList(
                    Files.exists(attrFile),
                    Files.isRegularFile(attrFile),
                    Files.isReadable(attrFile),
                    Files.isWritable(attrFile)
                ));
                actual.put("size_bytes", (int) Files.size(attrFile));
                actual.put("modified_time_millis", observedTime.toMillis());
                actual.put("posix_perm_count", parsedPerms.size());
                actual.put("owner_nonempty", owner != null && !owner.getName().isEmpty());
                actual.put("store_nonnull", store != null && store.getTotalSpace() > 0);
                actual.put("probe_content_type_ok", mime == null || mime.contains("text"));

                // Also call isExecutable to verify signature works cleanly
                Files.isExecutable(attrFile);

                cases.add(makeCase(
                    "nio_attributes_owner_filestore",
                    "验证 exists/isRegularFile/isReadable/isWritable/isExecutable/size、setLastModifiedTime、PosixFilePermissions 解析、getOwner 与 getFileStore",
                    expected,
                    actual
                ));
            }

            // Case 4: Temp files/dirs & Streams/Channels (createTempFile, createTempDirectory, newBufferedWriter/Reader, newOutputStream/InputStream, newByteChannel)
            {
                Path subTempDir = Files.createTempDirectory(workspace, "subtmp-");
                Path subTempFile = Files.createTempFile(subTempDir, "pref-", ".dat");

                try (BufferedWriter bw = Files.newBufferedWriter(subTempFile, StandardCharsets.UTF_8)) {
                    bw.write("buffered-line");
                }
                String readBackBuffered;
                try (BufferedReader br = Files.newBufferedReader(subTempFile, StandardCharsets.UTF_8)) {
                    readBackBuffered = br.readLine();
                }

                Path binFile = subTempDir.resolve("stream.bin");
                try (OutputStream os = Files.newOutputStream(binFile)) {
                    os.write(new byte[]{10, 20, 30, 40});
                }
                byte[] readBytes = new byte[4];
                int nRead;
                try (InputStream is = Files.newInputStream(binFile)) {
                    nRead = is.read(readBytes);
                }

                Path chanFile = subTempDir.resolve("chan.bin");
                try (SeekableByteChannel ch = Files.newByteChannel(
                        chanFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.READ)) {
                    ch.write(ByteBuffer.wrap("NIO".getBytes(StandardCharsets.UTF_8)));
                    ch.position(0);
                    ByteBuffer buf = ByteBuffer.allocate(3);
                    ch.read(buf);
                    buf.flip();
                    String chanText = StandardCharsets.UTF_8.decode(buf).toString();

                    Map<String, Object> expected = new LinkedHashMap<String, Object>();
                    expected.put("temp_prefix_suffix_ok", true);
                    expected.put("buffered_rw", "buffered-line");
                    expected.put("stream_bytes_count", 4);
                    expected.put("channel_text", "NIO");

                    Map<String, Object> actual = new LinkedHashMap<String, Object>();
                    actual.put("temp_prefix_suffix_ok",
                        subTempFile.getFileName().toString().startsWith("pref-")
                        && subTempFile.getFileName().toString().endsWith(".dat"));
                    actual.put("buffered_rw", readBackBuffered);
                    actual.put("stream_bytes_count", nRead);
                    actual.put("channel_text", chanText);

                    cases.add(makeCase(
                        "nio_temp_streams_and_channel",
                        "验证 createTempDirectory/createTempFile、newBufferedWriter/Reader、newOutputStream/InputStream 与 SeekableByteChannel",
                        expected,
                        actual
                    ));
                }
            }
        } finally {
            deleteRecursively(workspace);
        }

        Map<String, Object> root = new LinkedHashMap<String, Object>();
        root.put("version", "OpenJDK " + System.getProperty("java.version"));
        root.put("cases", cases);
        System.out.println(toJson(root));
    }
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。

入口文件:projects/java-nio-file-lab/ExploreNioFile.java

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 ExploreNioFile.java,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Java

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1138.zip

下载课程关联工程包:Java

课程关联工程包(登记关联57章) · 含当前章节或实例 · mbskycom202612a1104.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习