← 都来码 / Dolaima← 例程索引java/test/file_io.java原文

java/test/file_io.java · 2917 字节 · 下载原文

// file_io.java —— 文件读写示例(走 `Lib/shared/src/file.c` 的库实现)

// file_io.java — file read/write demo (going through the library in `Lib/shared/src/file.c`)

//

// ⚠ **原版是一个 5 行桩,从来没有编过**:它写的是

//   `asm("CALL shared_file_test")` / `asm("LOAD R0 #100")` / `asm("SYSCALL 3")`,而

//   ① Java 前端**有意移除了 `asm()`**(见 `JavaCompiler/CodeGenerator.Expressions.cs:869`:

//      "asm() 已移除 — 仅限 C/ObjC/C++ 语言使用"),

//   ② 它引用的 `shared_file_test` **在 `Lib/` 里根本不存在**(全库 grep 无命中)。

//   Swift 那份 `file_io.swift` 是同一个模子(同样的三行、同样的从没编过),已按同样的办法改掉。

// ⚠ **The original was a 5-line stub that never compiled**: it used `asm("CALL shared_file_test")` …

//   But the Java frontend deliberately removed `asm()` (see `CodeGenerator.Expressions.cs:869`), and

//   `shared_file_test` does not exist anywhere under `Lib/`. The Swift `file_io.swift` was the same

//   mould and has been rewritten the same way.

//

// ⚠ **不需要 `#include` 那些声明文件**:`file.vml` 是 Java 的**自动链接库**

//   (`Lib/java/builtin.vml` 里有 `.linked "file.vml"`)⇒ `fopen` 这些裸名由链接器解析。

// ⚠ **Do not `#include` a declaration file here**: `file.vml` is an auto-linked module for Java

//   (see `.linked "file.vml"` in `Lib/java/builtin.vml`), so the linker resolves the bare names.

//

// ⚠ **句柄是 0 起的**(第一个文件就是 0)—— 写成 `> 0` 会把成功判成失败。

// ⚠ **Handles start at 0** (the first open file is 0), so `> 0` would read success as failure.


class FileIO {
    public static void main(String[] a) {
        // 1) 只写打开(mode 1 = 建 + 截断),写 5 个字节

        // 1) Open for writing (mode 1 = create + truncate) and write 5 bytes

        int h = fopen("java_file_io.txt", 1);
        if (h >= 0) {
            fwrite(h, "hello", 5);
            fclose(h);
            System.out.println("WRITE=ok");
        } else {
            System.out.println("WRITE=open-failed");
        }

        // 2) 只读打开(mode 0),读回来 —— 这一半才是"写进去的到底是不是那 5 个字节"

        // 2) Open for reading (mode 0) and read it back — this half is what proves the bytes landed

        int h2 = fopen("java_file_io.txt", 0);
        if (h2 >= 0) {
            String buf = "     ";          // 5 格缓冲(数据段里的可写串)

            fread(h2, buf, 5);
            fclose(h2);
            System.out.println("CONTENT=" + buf);
        } else {
            System.out.println("CONTENT=reopen-failed");
        }
    }
}
// 期望(与别的语言的 `file_io.*` 同一份判据):

// EXPECT: WRITE=ok

// EXPECT: CONTENT=hello