Read/write to Windows registry using Java

前端 未结 24 1599
日久生厌
日久生厌 2020-11-21 05:45

How is it possible to read/write to the Windows registry using Java?

24条回答
  •  情话喂你
    2020-11-21 06:24

    You don't actually need a 3rd party package. Windows has a reg utility for all registry operations. To get the command format, go to the DOS propmt and type:

    reg /?
    

    You can invoke reg through the Runtime class:

    Runtime.getRuntime().exec("reg ");
    

    Editing keys and adding new ones is straightforward using the command above. To read the registry, you need to get reg's output, and it's a little tricky. Here's the code:

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.StringWriter;
    
    /**
     * @author Oleg Ryaboy, based on work by Miguel Enriquez 
     */
    public class WindowsReqistry {
    
        /**
         * 
         * @param location path in the registry
         * @param key registry key
         * @return registry value or null if not found
         */
        public static final String readRegistry(String location, String key){
            try {
                // Run reg query, then read output with StreamReader (internal class)
                Process process = Runtime.getRuntime().exec("reg query " + 
                        '"'+ location + "\" /v " + key);
    
                StreamReader reader = new StreamReader(process.getInputStream());
                reader.start();
                process.waitFor();
                reader.join();
                String output = reader.getResult();
    
                // Output has the following format:
                // \n\n\n\t\t
                if( ! output.contains("\t")){
                        return null;
                }
    
                // Parse out the value
                String[] parsed = output.split("\t");
                return parsed[parsed.length-1];
            }
            catch (Exception e) {
                return null;
            }
    
        }
    
        static class StreamReader extends Thread {
            private InputStream is;
            private StringWriter sw= new StringWriter();
    
            public StreamReader(InputStream is) {
                this.is = is;
            }
    
            public void run() {
                try {
                    int c;
                    while ((c = is.read()) != -1)
                        sw.write(c);
                }
                catch (IOException e) { 
            }
            }
    
            public String getResult() {
                return sw.toString();
            }
        }
        public static void main(String[] args) {
    
            // Sample usage
            String value = WindowsReqistry.readRegistry("HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\" 
                     + "Explorer\\Shell Folders", "Personal");
            System.out.println(value);
        }
    }
    

提交回复
热议问题