如何用java设置系统时间?

如题所述

使用ProcessBuilder类操作。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;

public class TestProcessBuilder
{
public static void main ( String[] args ) throws Exception
{
ProcessBuilder builder = new ProcessBuilder ("cmd", "/c", "time 06:19:28.25");
Process process = builder.start ();
InputStream is = process.getInputStream ();
InputStreamReader isr = new InputStreamReader (is, "GBK");
BufferedReader br = new BufferedReader (isr);
while (null != ( line = br.readLine () ))
{
System.out.println (line);
}
br.close ();
isr.close ();
is.close ();
process.destroy ();
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-05-31
import java.io.IOException;
public class SetTime {
public static void main(String args[]){
String osName = System.getProperty("os.name");
String cmd = "";
try {
if (osName.matches("^(?i)Windows.*$")) {// Window 系统
// 格式 HH:mm:ss
cmd = " cmd /c time 22:35:00";
Runtime.getRuntime().exec(cmd);
// 格式:yyyy-MM-dd
cmd = " cmd /c date 2009-03-26";
Runtime.getRuntime().exec(cmd);
} else {// Linux 系统
// 格式:yyyyMMdd
cmd = " date -s 20090326";
Runtime.getRuntime().exec(cmd);
// 格式 HH:mm:ss
cmd = " date -s 22:35:00";
Runtime.getRuntime().exec(cmd);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
第2个回答  2011-02-26
import java.io.IOException;
public class SetTime {
public static void main(String args[]){
String osName = System.getProperty("os.name");
String cmd = "";
try {
if (osName.matches("^(?i)Windows.*$")) {// Window 系统
// 格式 HH:mm:ss
cmd = " cmd /c time 22:35:00";
Runtime.getRuntime().exec(cmd);
// 格式:yyyy-MM-dd
cmd = " cmd /c date 2009-03-26";
Runtime.getRuntime().exec(cmd);
} else {// Linux 系统
// 格式:yyyyMMdd
cmd = " date -s 20090326";
Runtime.getRuntime().exec(cmd);
// 格式 HH:mm:ss
cmd = " date -s 22:35:00";
Runtime.getRuntime().exec(cmd);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}追问

是调用系统的命令吧?

追答

恩,调用的命令行,只能支持windows和linux系统

本回答被提问者采纳