在项目中要用到一些小功能,使用java代码控制电脑的关机,重启,截屏。最好是封装成方法,方便能够直接调用。
public class Test {
// 默认60秒后关机
public void shutdown() {
// 关机
try {
Runtime.getRuntime().exec("shutdown /s /t 60");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 根据输入的时间秒数关机
public void shutdown(String s) {
try {
// 关机
Runtime.getRuntime().exec("shutdown /s /t " + s); //关机时间可以自动设置
} catch (IOException e) {
e.printStackTrace();
}
}
// 重启
public void restart() {
try {
Runtime.getRuntime().exec("shutdown -r ");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/* 截屏screenshot
* 参数:图片存放的位置
* 返回: 生成图片生成的路径,图片格式是png,也可以根据自己的需要进行修改
*/
public String screenShot(String fileName) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
String randomName = UUID.randomUUID().toString().replace("-", "");
String name = randomName + ".png";
// 截图保存的路径
File screenFile = new File(fileName);
Robot robot;
String path = "";
boolean b = false;
try {
robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
File f = new File(screenFile, name);
b =ImageIO.write(image, "png", f);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(b){
path = fileName + File.separator +name;
}
return path;
}
}
控制电脑关机和重启只有一行代码。截屏的需要设置存放路径,有多行。
这里面没有需要外引的jar包。