0% found this document useful (0 votes)
10 views

MY Java Snippet

This code snippet shows how to get the process ID (PID) of a running Java application at runtime. It uses the ManagementFactory class to get the name of the running Java Virtual Machine, finds the index of the @ symbol in the name to separate the PID, and prints out the PID.

Uploaded by

Sawan Singh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

MY Java Snippet

This code snippet shows how to get the process ID (PID) of a running Java application at runtime. It uses the ManagementFactory class to get the name of the running Java Virtual Machine, finds the index of the @ symbol in the name to separate the PID, and prints out the PID.

Uploaded by

Sawan Singh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

Java snippet: get PID at runtime

package my.pid; import java.lang.management.ManagementFactory; public class MyPid { public static void main(String[] args) { String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getNa me(); int p = nameOfRunningVM.indexOf('@'); String pid = nameOfRunningVM.substring(0, p); System.out.println("Java app PID: " + pid); } }

Code Snippet: Redirecting Standard Output to File


1. import java.io.FileNotFoundException; 2. import java.io.FileOutputStream; 3. import java.io.PrintStream; 4. 5. 6. public class SystemOutRedirect { 7. 8. public static void main(String[] args) throws FileNotFoundException { 9. System.setOut(new PrintStream(new FileOutputStream("stdout.txt"))); 10. System.setErr(new PrintStream(new FileOutputStream("error.txt"))); 11. 12. System.out.println("hello"); //goes to stdout.txt 13. System.err.println("error"); //goes to error.txt 14. } 15. 16. }

You might also like