我有这段代码
package Classes;
import java.io.*;
public class IpAdministrator {
public Boolean isActive(String ipAddress) {
boolean isActive = false;
String cmd;
String OS = System.getProperty("os.name");
System.out.println(OS);
String tmpfolder = System.getProperty("java.io.tmpdir");
System.out.println(tmpfolder);
//iptmp.deleteOnExit();
if (OS.equals("Linux")) {
cmd = "ping " + ipAddress + " -c 1";
} else {
cmd = "cmd /c ping " + ipAddress + " -n 1";
}
try {
String s = null;
Process p = Runtime.getRuntime().exec(cmd);
File iptmp = File.createTempFile("ipresult", ".txt", new File(tmpfolder));
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
s = s.toString();
BufferedWriter writer = new BufferedWriter(new FileWriter(iptmp));
writer.write(s);
}
} catch (Exception ex) {
System.out.println(ex.getMessage().toString());
}
return isActive;
}
}
Run Code Online (Sandbox Code Playgroud)
我想从临时文件中的命令中写出结果,我发现在这个网站的其他问题中有相关的东西,它似乎工作正常,但是当我运行这个时,文件是用一些随机的数字创建的(即:ipresult540677216848957037 .txt)并且它是空的,我无法弄清楚为什么,我也读到它与java 1.7相关的东西,所以这意味着我无法用信息填充文件,有什么我缺少的东西?
每次打开文件以便以这种方式编写时 - 即每次执行此行时:
BufferedWriter writer = new BufferedWriter(new FileWriter(iptmp));
Run Code Online (Sandbox Code Playgroud)
该文件被截断为零长度.此外,由于你从未明确地调用close()过BufferedWriter,你写的行永远不会真正刷新到文件.结果,没有数据进入磁盘.
要正确执行此操作,首先,将上面的行移到循环之前,因此它只执行一次.其次,循环之后,包括代码之类的
if (writer != null)
writer.close();
Run Code Online (Sandbox Code Playgroud)
最后,请注意您的程序在Mac上是不必要的,它既不是Linux,也不是它们使用的cmd.exe.而不是你写这个的方式,你明确测试Windows,如果你找到它,使用Windows命令行; 否则,假设类似UNIX,并使用Linux版本.