Java:如何确定 1.6 之前的 Windows 系统上的磁盘空间
我想确定 Windows 上的可用磁盘空间。 我不在乎我的代码不可移植。 我使用这个:
String[] command = {"dir",drive};
Process process = Runtime.getRuntime().exec(command);
InputStream result = process.getInputStream();
旨在解析“dir C:”类型的调用的结果,但是从命令行调用中获得的字符串就像我使用 /W
选项调用 dir (不是提供有关文件大小或磁盘使用/可用空间的任何信息)。 (尽管当我直接从命令行启动 dir C:
时,我得到了预期的结果,因此我的系统上没有 dir
特定设置。) token /-W
或任何其他选项似乎都不起作用:我只获取驱动器中包含的文件夹/文件的名称,但没有任何其他信息。
有人知道修复/解决方法吗?
注意:
我无法采用 fsutil
路线,因为 fsutil
不适用于网络驱动器。
I want to determine the available disk space on windows. I don't care that my code is not portable. I use this :
String[] command = {"dir",drive};
Process process = Runtime.getRuntime().exec(command);
InputStream result = process.getInputStream();
aiming to parse the result from a "dir C:" type of call, but the String I get from the command line call is as if I called dir with a /W
option (not giving any information about file sizes or disk usage / free space). (Although when I launch dir C:
directly from the command line, I get the expected result, so there is no dir
particular setup on my system.) Trying to pass a token /-W
or on any other option seems not to work : I just get the name of the folders/files contained in the drive, but no other information whatsoever.
Someone knows a fix / workaround ?
NOTE:
I can't go along the fsutil
route, because fsutil
does not work on network drives.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来你的 exec() 正在你的路径中的某个地方找到一个名为“dir”的程序,因为使用你的 String[] 命令,否则我希望你得到
IOException(系统找不到指定的文件)
。 标准 dir 命令内置于 cmd.exe 命令提示符中,并不是可以单独执行的独立程序。要运行 cmd.exe 中内置的 dir 命令,您需要在 cmd.exe 上使用 /c 开关,该开关执行指定的命令,然后退出。 因此,如果您想执行:
传递给 exec 的参数将是:
It sounds like your
exec()
is finding a program called "dir" somewhere in your path because with yourString[] command
as it is I would otherwise expect you to get anIOException (The system cannot find the file specified)
. The standard dir command is built into the cmd.exe Command Prompt and is not a standalone program you can execute in its own right.To run the dir command built into cmd.exe you need to use the /c switch on cmd.exe which executes the specified command and then exits. So if you want to execute:
your arguments to pass to exec would be:
如果您不关心可移植性,请使用 Win32 API 中的 GetDiskFreeSpaceEx 方法。 使用 JNI 和 viola 包装它!
您的 Java 代码应如下所示:
其余部分可以通过此处的示例完成。 我认为虽然 JNI 存在性能问题,但它不太可能导致 痛苦通过使用 Process 类,您将忍受......
If you don't care about portability, use the GetDiskFreeSpaceEx method from Win32 API. Wrap it using JNI, and viola!
Your Java code should look like:
and the rest can be done through the example here. I think that while JNI has its performance problems, it is less likely to cause the amount of pain you'll endure by using the Process class....
Apache Commons 有 FileSystemUtils.freeSpaceKb() 将跨平台工作等
Apache Commons has FileSystemUtils.freeSpaceKb() that will work cross platfrom etc etc