以下是Java操作Windows系统功能的几个案例:
- 打开系统默认浏览器:
Desktop.getDesktop().browse(URI.create("http://www.google.com"));
- 打开文件夹:
FileManager fileManager = new FileManager();
fileManager.openFolder("C:\\Users");
public class FileManager {
public void openFolder(String path) {
try {
Runtime.getRuntime().exec("explorer.exe /select,"+path);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 播放音频:
MediaPlayer mediaPlayer = new MediaPlayer(new Media(new File("E:/music.mp3").toURI().toString()));
mediaPlayer.play();
public class MediaPlayer {
private final Media media;
private final javafx.scene.media.MediaPlayer player;
public MediaPlayer(Media media) {
this.media = media;
player = new javafx.scene.media.MediaPlayer(media);
}
public void play() {
player.play();
}
public void pause() {
player.pause();
}
public void stop() {
player.stop();
}
}
- 打开命令行并执行命令:
CMD.execute("cmd /c dir");
public class CMD {
public static void execute(String command) {
try {
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}