You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何绕过文件系统直接向驱动器写入字节?Java实现遇阻求助

驱动器级别的字节写入解决方案

Java实现修正

你的代码报错是因为把驱动器根目录当成了普通文件,Windows系统中需要使用设备路径才能将整个驱动器视为可操作的“大文件”。修正后的代码如下:

try {
    // Windows设备路径格式:\\\\.\\盘符:
    Path drivePath = Path.of("\\\\.\\W:");
    FileChannel channel = FileChannel.open(drivePath, StandardOpenOption.READ, StandardOpenOption.WRITE);
    MappedByteBuffer buff = channel.map(FileChannel.MapMode.READ_WRITE, 4206944, 6);
    byte[] write = new byte[] {0x2F, 0x10, 0x50, 0xDA, 0x00, 0x10};
    buff.put(write);
    buff.force();
    channel.close();
} catch (IOException e) {
    throw new RuntimeException(e);
}

注意:

  • 必须以管理员权限运行程序,否则会抛出权限不足的异常
  • 该方式仅适用于Windows系统,跨平台场景需要额外处理

其他语言实现选项

如果Java的方案存在兼容性限制,以下语言可以更直接地实现驱动器级操作:

C#

using System.IO;

class DriveWriter
{
    static void Main()
    {
        using (var driveStream = new FileStream(@"\\.\W:", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            driveStream.Seek(4206944, SeekOrigin.Begin);
            byte[] writeBytes = new byte[] {0x2F, 0x10, 0x50, 0xDA, 0x00, 0x10};
            driveStream.Write(writeBytes, 0, writeBytes.Length);
        }
    }
}

同样需要管理员权限运行,代码简洁且原生支持设备路径访问。

C/C++

借助Windows原生API直接操作驱动器设备:

#include <windows.h>
#include <iostream>

int main()
{
    HANDLE driveHandle = CreateFile(L"\\\\.\\W:", 
                                    GENERIC_READ | GENERIC_WRITE, 
                                    FILE_SHARE_READ | FILE_SHARE_WRITE, 
                                    nullptr, 
                                    OPEN_EXISTING, 
                                    0, 
                                    nullptr);

    if (driveHandle == INVALID_HANDLE_VALUE)
    {
        std::cerr << "打开驱动器失败,错误码: " << GetLastError() << std::endl;
        return 1;
    }

    LARGE_INTEGER offset;
    offset.QuadPart = 4206944;
    SetFilePointerEx(driveHandle, offset, nullptr, FILE_BEGIN);

    BYTE writeBytes[] = {0x2F, 0x10, 0x50, 0xDA, 0x00, 0x10};
    DWORD bytesWritten;
    WriteFile(driveHandle, writeBytes, sizeof(writeBytes), &bytesWritten, nullptr);

    CloseHandle(driveHandle);
    return 0;
}

该方式是最底层的实现,性能最高,但需要处理Windows API的错误逻辑,同样要求管理员权限。

内容的提问来源于stack exchange,提问作者milkchunks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.02 00:03:10