- Можно ли выключить компьютер из кода Java?
- 2 ответа
- РЕДАКТИРОВАТЬ
- Java Program To Shutdown Computer in Windows
- 1. Introduction
- 2. Java Program To Shutdown Computer
- 3. Conclusion
- SHARE:
- About Us
- Java 8 Tutorial
- Java Threads Tutorial
- Kotlin Conversions
- Kotlin Programs
- Java Conversions
- Java String API
- Spring Boot
- $show=Java%20Programs
- $show=Kotlin
- Выключение компьютера
- 9 ответов
- Java Program to Shutdown and Restart Computer
- Shutdown Computer after 5 Seconds in Java
- Shutdown Computer after Given Time (in Seconds)
- Restart Computer after 5 Seconds in Java
- Restart Computer after Given Seconds
- Same Program in Other Languages
Можно ли выключить компьютер из кода Java?
В классе программирования для начинающих нам было поручено хранить оценки класса, средний, самый низкий балл, самый высокий балл и т. Д.
Нас также попросили выключить компьютер.
Я вывел меню, и одним из случаев было выключение компьютера.
Однако это не работает. Метод 4 и метод 8 — единственные, связанные с проблемой.
import javax.swing.*; import java.io.*; class ClassMarks < String names[]; int marks[]; int counter; String marksString; final String PASSWORD = "Top Secret"; String name, surname; int mark; int total; double average; //method to check password public void checkPassword() < int counter = 0; String password_user; do < password_user = JOptionPane.showInputDialog("Enter password: "); if (password_user.equals(PASSWORD)) < JOptionPane.showMessageDialog(null, "Access Granted"); outputMenu(); >else < JOptionPane.showMessageDialog(null, "Access Denied"); >counter++; > while ((counter < 4) && !(password_user.equals(PASSWORD))); JOptionPane.showMessageDialog(null, "No more attempts available"); >public void compulsoryMethod() < String namesString = JOptionPane.showInputDialog("Enter number of students"); int noOfNames = Integer.parseInt(namesString); //print all the array elements for (counter = 0; counter < noOfNames; counter++) < names[counter] = JOptionPane.showInputDialog("Enter names"); marksString = JOptionPane.showInputDialog("Enter Mark for" + names[counter] + " "); marks[counter] = Integer.parseInt(marksString); >> // method 4 public void outputMenu() < int input; do < String stringInput = JOptionPane.showInputDialog("Choose the decision you want to make: \n\n 1.Enter marks \n 2. See marks \n 3.Find Average \n 4.See highest mark \n 5.See lowest mark \n 6.See any mark above average \n 7.Turn off this Pc/Laptop/any other device\n 8.See Grade"); input = Integer.parseInt(stringInput); // to convert stringInput which is String to input which is int switch (input) < case 1: enterMarks(); break; case 2: viewMarks(); break; case 3: averageMark(); break; case 4: highestMark(); break; case 5: lowestMark(); break; case 6: markAboveAverage(); break; case 7: shutDown(); break; case 8: viewMarks(); break; default: JOptionPane.showMessageDialog(null, "Invalid choice"); >> while (input != 7); > //method 3 public void enterMarks() < String namesString = JOptionPane.showInputDialog("Enter no of students:"); int noOfNames = Integer.parseInt(namesString); names = new String[noOfNames]; marks = new int[noOfNames]; for (counter = 0; counter < marks.length; counter++) < names[counter] = JOptionPane.showInputDialog("Enter names:"); marksString = JOptionPane.showInputDialog("Enter Mark for " + names[counter] + " "); marks[counter] = Integer.parseInt(marksString); >> // method 5 public void viewMarks() < for (counter = 0; counter < marks.length; counter++) < JOptionPane.showMessageDialog(null, new JTextArea(names[counter] + "\t\t" + marks[counter] + "\t\t" + displayGrade(marks[counter]))); >> //method 6 public void averageMark() < int total = 0; for (counter = 0; counter < marks.length; counter++) < total = total + marks[counter]; >average = total / 5; JOptionPane.showMessageDialog(null, "Average is:" + average); > //method 7 public void highestMark() < int large = 0; int num; // i starts from 2 because we already took one num value for (int counter = 0; counter < marks.length; counter++) < if (marks[counter] >large) < large = marks[counter]; >> JOptionPane.showMessageDialog(null, large); > //method 8 public void lowestMark() < int small = 100; int num; for (int counter = 0; counter < marks.length; counter++) < if (marks[counter] < small) < small = marks[counter]; >> JOptionPane.showMessageDialog(null, small); > //method 9 public void markAboveAverage() < averageMark(); for (int counter = 0; counter < marks.length; counter++) < if (marks[counter] >average) < JOptionPane.showMessageDialog(null, marks[counter] + ": This mark is above average"); >else < JOptionPane.showMessageDialog(null, marks[counter] + "This mark is below average"); >> > //method 10 public void (main String[]) throws IOException < Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec("shutdown -s -t 0"); System.exit(0); >//method11 public char displayGrade(int marks) < char grade = ' '; if ((marks >= 0) && (marks if ((marks >= 21) && (marks if ((marks >= 41) && (marks if ((marks >= 61) && (marks if ((marks >= 81) && (marks if ((marks >= 91) && (marks return grade; > >
2 ответа
Вы можете использовать команду CMD, чтобы закрыть или перезагрузить компьютер, как
Вот способ закрыть и перезагрузить компьютер, используя Windows:
Выключите компьютер:
public void shutdownPC(int time) < try < Runtime r = Runtime.getRuntime(); // Shutdown system time mean, time to wait before my system will shutdow or restart r.exec("shutdown -s -t " + time); >catch (NumberFormatException | IOException e) < JOptionPane.showMessageDialog(null, "Restart failed."); >>
Перезагрузите компьютер:
public void restartPC(int time) < try < Runtime r = Runtime.getRuntime(); // Restart system r.exec("shutdown -r -t " + time); >catch (NumberFormatException | IOException e) < JOptionPane.showMessageDialog(null, "Restart failed."); >>
Если вы используете Linux или Mac, вы можете использовать эти две команды:
Вы можете узнать о командной строке Linux и Mac
РЕДАКТИРОВАТЬ
Вы получаете и ошибка в 4-м методе в случае 7, потому что вы вызываете shutDown(); , и это не существует в вашем коде, поэтому вы должны вызвать правильный метод.
Вы получаете ошибку в основном методе public void (main String[]) throws IOException < потому что он не создан правильно, поэтому вам нужно создать его так:
public static void main(String[] args) throws IOException < //your code here >
не забыл импортировать это import java.io.IOException;
И о двух методах, которые я установил в предыдущем ответе, вы должны сделать их статическими:
public static void shutdownPC(int time) <> public static void restartPC(int time) <>
И чтобы вызвать их из вашего метода 4, вам нужно указать время для перезагрузки или выключения вашего компьютера следующим образом:
case 7: shutdownPC(5);//5 mean 5 second if you want to shut the pc imidattilly just set it 0 break;
Java Program To Shutdown Computer in Windows
Java program to shutdown computer in windows machine. Example program to use command «shutdown -s -t» with after a specified time in seconds.
1. Introduction
In this tutorial, We’ll learn how to shut down computers in java using a command «shutdown -s -t». It takes time when you want to do shutdown the computer.
2. Java Program To Shutdown Computer
The below program takes the number of seconds as input and will use the Runtime class to execute the windows command with the help of exec() method.
package com.java.w3schools.blog.java.program.to; import java.io.IOException; import java.util.Scanner; /** * * Shutdown in java. * * @author JavaProgramTo.com * */ public class ShutdownComputer < public static void main(String[] args) throws IOException < Scanner scanner = new Scanner(System.in); System.out.println("Enter the time that you want to shutdown after some amount of time : "); Double timeInSeconds = scanner.nextDouble(); Runtime runtime = Runtime.getRuntime(); Process p = runtime.exec("shutdown -s -t " + timeInSeconds); System.exit(1); >>
3. Conclusion
In this article, We’ve seen how to shut down the computer in java with windows operating systems. The example is shown with the Runtime class exec() method.
SHARE:
About Us
Java 8 Tutorial
- Java 8 New Features
- Java 8 Examples Programs Before and After Lambda
- Java 8 Lambda Expressions (Complete Guide)
- Java 8 Lambda Expressions Rules and Examples
- Java 8 Accessing Variables from Lambda Expressions
- Java 8 Method References
- Java 8 Functional Interfaces
- Java 8 — Base64
- Java 8 Default and Static Methods In Interfaces
- Java 8 Optional
- Java 8 New Date Time API
- Java 8 — Nashorn JavaScript
Java Threads Tutorial
Kotlin Conversions
Kotlin Programs
Java Conversions
- Java 8 List To Map
- Java 8 String To Date
- Java 8 Array To List
- Java 8 List To Array
- Java 8 Any Primitive To String
- Java 8 Iterable To Stream
- Java 8 Stream To IntStream
- String To Lowercase
- InputStream To File
- Primitive Array To List
- Int To String Conversion
- String To ArrayList
Java String API
- charAt()
- chars() — Java 9
- codePointAt()
- codePointCount()
- codePoints() — Java 9
- compareTo()
- compareToIgnoreCase
- concat()
- contains()
- contentEquals()
- copyValueOf()
- describeConstable() — Java 12
- endsWith()
- equals()
- equalsIgnoreCase()
- format()
- getBytes()
- getChars()
- hashcode()
- indent() — Java 12
- indexOf()
- intern()
- isBlank() — java 11
- isEmpty()
- join()
- lastIndexOf()
- length()
- lines()
- matches()
- offsetByCodePoints()
- regionMatches()
- repeat()
- replaceFirst()
- replace()
- replaceAll()
- resolveConstantDesc()
- split()
- strip(), stripLeading(), stripTrailing()
- substring()
- toCharArray()
- toLowerCase()
- transform() — Java 12
- valueOf()
Spring Boot
$show=Java%20Programs
$show=Kotlin
accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
Java program to shutdown computer in windows machine. Example program to use command «shutdown -s -t» with after a specified time in seconds.
Выключение компьютера
Есть ли способ выключить компьютер с помощью встроенного метода Java?
9 ответов
Создайте свою собственную функцию для выполнения команды ОС через командную строку?
Ради примера. Но знайте, где и почему вы хотите использовать это, как отмечают другие.
public static void main(String arg[]) throws IOException
Быстрый ответ — нет. Единственный способ сделать это — вызвать специфичные для ОС команды, которые приведут к выключению компьютера, если у вашего приложения есть необходимые привилегии для этого. Это по своей сути непереносимо, поэтому вам нужно либо знать, где будет запускаться ваше приложение, либо иметь разные методы для разных ОС и определять, какой из них использовать.
Я использую эту программу для выключения компьютера за X минут.
public class Shutdown < public static void main(String[] args) < int minutes = Integer.valueOf(args[0]); Timer timer = new Timer(); timer.schedule(new TimerTask() < @Override public void run() < ProcessBuilder processBuilder = new ProcessBuilder("shutdown", "/s"); try < processBuilder.start(); >catch (IOException e) < throw new RuntimeException(e); >> >, minutes * 60 * 1000); System.out.println(" Shutting down in " + minutes + " minutes"); > >
Лучше использовать .startsWith, чем использовать .equals .
String osName = System.getProperty("os.name"); if (osName.startsWith("Win")) < shutdownCommand = "shutdown.exe -s -t 0"; >else if (osName.startsWith("Linux") || osName.startsWith("Mac")) < shutdownCommand = "shutdown -h now"; >else < System.err.println("Shutdown unsupported operating system . "); //closeApp(); >
Пока кто-нибудь не использует новую ОС под названием Macaroni, где выключение — это команда самоуничтожения.
В Windows Embedded по умолчанию в cmd нет команды выключения. В таком случае вам нужно добавить эту команду вручную или использовать функцию ExitWindowsEx из win32 (user32.lib) с помощью JNA (если вы хотите больше Java) или JNI (если вам проще будет установить привилегии в коде C).
Runtime.getRuntime().exec("shutdown -s -t 0");
Но работает только с окнами
Java Program to Shutdown and Restart Computer
This article is created to cover multiple programs in Java, to shutdown or restart the computer system. Here are the list of programs included in this article:
- Shutdown computer after 5 seconds using Java
- Shutdown computer after given time using Java
- Restart computer after 5 seconds using Java
- Restart computer after given time using Java
To shutdown computer in Java programming, you have to use the command shutdown -s. You can also specify the time in seconds, after which you want to turn off or shutdown the PC, using shutdown -s -t seconds. Where seconds refers to the number of seconds.
Note — To shutdown the computer, use shutdown -s. To restart the computer, use shutdown -r.
Important — Be sure to close all unsaved files and windows, before executing the program given below, to shutdown or restart the computer system.
Shutdown Computer after 5 Seconds in Java
The question is, write a Java program to shutdown the computer after 5 seconds. Answer to this question, is the program given below:
import java.io.*; public class CodesCracker < public static void main(String[] args) < Runtime runtime = Runtime.getRuntime(); try < System.out.println("Shutting down the PC after 5 seconds."); runtime.exec("shutdown -s -t 5"); > catch(IOException e) < System.out.println("Exception: " +e); > > >
The sample output produced by this program is:
Shutting down the PC after 5 seconds.
and the PC will get shutdown after 5 seconds.
Shutdown Computer after Given Time (in Seconds)
This program receives the number of seconds from user at run-time of the program, to shutdown the computer after the given number of seconds.
import java.util.Scanner; import java.io.*; public class CodesCracker < public static void main(String[] args) < Scanner scan = new Scanner(System.in); System.out.print("Enter the Number of Seconds: "); int seconds = scan.nextInt(); Runtime r = Runtime.getRuntime(); try < System.out.println("Shutting down the PC after " +seconds+" seconds."); r.exec("shutdown -s -t " +seconds); > catch(IOException e) < System.out.println("Exception: " +e); > > >
The snapshot given below shows the initial output produced by above program, on shutting down the computer after given number of seconds:
Now type the number of seconds and press ENTER key to initiate the shutdown operation after that number of seconds. For example, type 60 and press ENTER key to shutdown PC after 60 seconds.
Restart Computer after 5 Seconds in Java
The only change we need to do, from the program given in the section Shutdown Computer after 5 Seconds in Java, is to change the code from shutdown -s -t to shutdown -r -t, to restart the computer after 5 seconds. Here is the complete version of the program.
import java.io.*; public class CodesCracker < public static void main(String[] args) < Runtime r = Runtime.getRuntime(); try < r.exec("shutdown -r -t 5"); System.out.println("Restarting the Computer after 5 seconds."); > catch(IOException e) < System.out.println("Exception: " +e); > > >
Restart Computer after Given Seconds
This is the last program of this article, created to restart the computer after given number of seconds, by user at run-time of the program:
import java.util.Scanner; import java.io.*; public class CodesCracker < public static void main(String[] args) < Scanner scan = new Scanner(System.in); System.out.print("Enter the Number of Seconds: "); int sec = scan.nextInt(); Runtime r = Runtime.getRuntime(); try < System.out.println("The PC will get restarted after " +sec+" seconds."); r.exec("shutdown -r -t " +sec); > catch(IOException e) < System.out.println("Exception: " +e); > > >
Note — To shutdown or restart PC immediately, use shutdown -s -t 0 or shutdown -r -t 0.
Note — If you’ll not use the time, then by default, the computer will get shutdown/restart after 30 seconds using shutdown -s or shutdown -r.
Same Program in Other Languages
Liked this article? Share it!