执行一个net use命令 [英] Executing a net use command

查看:363
本文介绍了执行一个net use命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行这是写在一个批处理文件,以使驱动器net use命令。批处理文件如下:

净使用* /删除/ Y
NET USE L:\\\\< Windows驱动器名称> /用户:其中结构域GT; \\<用户名> <密码和GT;

以上的批处理文件使我的一个驱动器及其为L可见:开车到我。
我需要通过Java code来执行这个批处理文件,然后将某些文件写入到该驱动器。

我使用的是低于code来执行这个批处理文件:

  String []数组= {CMD,/ C,开始,C:/file.bat};
调用Runtime.getRuntime()EXEC(阵列)。

问题是,当我尝试访问该驱动器来写它给了我未发现异常路径的文件。有时运行,有时没有。

友谁能帮助我了解在哪里的问题。我执行什么走错一步。如果我不清楚我的问题不要让我知道。


解决方案

  

有时候运行,有时没有。


这看起来像一个竞争条件。 <一href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec%28java.lang.String%5B%5D%29\"相对=nofollow> 的Runtime.exec() 在一个单独的进程执行您的命令,而调用应用程序继续运行。然后,它是未定义或批处理文件是否已经完成而不是当您尝试访问该文件。

的Runtime.exec()返回过程对象,您可以使用与子进程通信。根据你的情况,应该是足够的等待过程来完成:

 进程p =调用Runtime.getRuntime()EXEC(阵列)。
p.waitFor();//现在,您的批处理文件应完成并可以继续
// ...

I need to execute a net use command which is written in a batch file to enable a drive. Batch file is as follows:

net use * /delete /Y
net use l: \\<windows drive name> /user:<domain>\<username> <password>

The above batch file enables a drive for me and its visible as L: drive to me. I need to execute this batch file through java code and then write the some files onto this drive.

I am using the below code to execute this batch file:

String[] array = { "cmd", "/C", "start", "C:/file.bat" };
Runtime.getRuntime().exec(array);

Problem is when I try to access the drive to write the files it gives me a path not found exception. Sometimes it runs and sometimes it doesn't.

Friends can anyone help me to understand where is the issue. What wrong step I am performing. In case I am not clear with my question do let me know.

解决方案

Sometimes it runs and sometimes it doesn't.

This looks like a race condition. Runtime.exec() executes your command in a separate process, while the calling application continues to run. It is then undefined whether the batch file has already completed or not when you try to access the file.

Runtime.exec() returns a Process object, which you can use to communicate with the sub process. In your case, it should be sufficient to wait for the process to complete:

Process p = Runtime.getRuntime().exec(array);
p.waitFor();

// Now, your batch file should be completed and you can continue
// ...

这篇关于执行一个net use命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆