java修改操作系统时间(linux和windows)

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.Test;
public class TestModifySysDate {
@Test
public void getSysdate1(){
DateFormat chinaFormatter=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM,Locale.CHINA);
DateFormat defaultFormatter=DateFormat.getDateTimeInstance();
Date now=new Date();
DateFormat gmt08Formatter=DateFormat.getDateTimeInstance();
TimeZone timezone=TimeZone.getTimeZone( “GMT 08:00 “);
gmt08Formatter.setTimeZone(timezone); //格式日期/时间
String defaultDateTime=defaultFormatter.format(now);
String chinaDateTime=chinaFormatter.format(now);
String gmt08DateTime=gmt08Formatter.format(now);
System.out.print( defaultDateTime+” ” +chinaDateTime+” “+ gmt08DateTime);
}

@Test
//修改window7时间
public void modifyTime(){
    try {
           Process p = Runtime.getRuntime().exec("cmd /c time 08:55:00");
        //   p.waitFor();
           BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

           if (!br.ready()) {
            Thread.sleep(100);
           }
           while (true) {
            String s = br.readLine();
            if (s == null)
             break;
            System.out.println(s);
           }
           br.close();
          } catch (Exception e) {
           e.printStackTrace();
          }
}

@Test
//修改windows7日期
public void modifyDate(){
     String date="2015-06-15";
            try{
                Runtime run=Runtime.getRuntime();
                String command="cmd.exe /c date"+" "+(date);     
                run.exec(command); 
            }
            catch(Exception e)
            {
             e.printStackTrace();
            }
}
//linux下修改时间和日期

public static void main(String args[]) throws Exception{
FileWriter excutefw = new FileWriter(“/usr/updateSysTime.sh”);
BufferedWriter excutebw=new BufferedWriter(excutefw);
excutebw.write(“date -s \”2015-12-01 00:00:00\”\r\n”);
excutebw.write(“clock -w”);
excutebw.close();
excutefw.close();
String cmd_date =”sh /usr/updateSysTime.sh”;
Runtime.getRuntime().exec(cmd_date);
}
}
}

你可能感兴趣的:(java,linux,操作系统)