Read/write to Windows registry using Java

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

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

24条回答
  •  面向向阳花
    2020-11-21 06:21

    Here's a modified version of Oleg's solution. I noticed that on my system (Windows server 2003), the output of "reg query" is not separated by tabs ('\t'), but by 4 spaces.

    I also simplified the solution, as a thread is not required.

    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);
    
          InputStream is = process.getInputStream();
          StringBuilder sw = new StringBuilder();
    
          try
          {
             int c;
             while ((c = is.read()) != -1)
                 sw.append((char)c);
          }
          catch (IOException e)
          { 
          }
    
          String output = sw.toString();
    
          // Output has the following format:
          // \n\n\n        \r\n\r\n
          int i = output.indexOf("REG_SZ");
          if (i == -1)
          {
              return null;
          }
    
          sw = new StringBuilder();
          i += 6; // skip REG_SZ
    
          // skip spaces or tabs
          for (;;)
          {
             if (i > output.length())
                 break;
             char c = output.charAt(i);
             if (c != ' ' && c != '\t')
                 break;
             ++i;
          }
    
          // take everything until end of line
          for (;;)
          {
             if (i > output.length())
                 break;
             char c = output.charAt(i);
             if (c == '\r' || c == '\n')
                 break;
             sw.append(c);
             ++i;
          }
    
          return sw.toString();
      }
      catch (Exception e)
      {
          return null;
      }
    

    }

提交回复
热议问题