linux上的注册文件转windows,用java实现向注册表添加注册文件,包含xml转map

<?xml version="1.0" encoding="UTF-8" ?>
<config>
    <TYP>0</TYP>
    <LEN>2</LEN>
    <MOD>0</MOD>
    <RN>0</RN>
    <HN>2</HN>
    <SCN>0</SCN>
    <PD>0</PD>
    <KR>UqknrfHqnydqdjra</KR>
    <PARAM>pX3nftWedUAe8ngi</PARAM>
    <HT>6ee837327883701449e65c41af3538d14da65465f4046c1bae4c22a90e8c35f73849e32c936598baa9bfe7bba2d49885ee4c5fa1e8d57e361a162e97c62143c4</HT>
</config>

首先我们通过xftp将linux的注册文件拿过来,下面使用xml读取出xml的内容 xftp下载链接

package com.reader.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.util.Assert;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlReader {
    private String path;
    private URL url;
    private List<Element> elements = new ArrayList<>();
    private Map<String, Object> map = new HashMap<>();
    private Element rootElement;
    public XmlReader(String path){
        this.path = path;
        parseByPath();
    }
    public XmlReader(URL url) throws DocumentException {
        this.url = url;
        parseByUrl();
    }
    public Document parseByUrl() throws DocumentException {
        Assert.isTrue(this.url!=null, "url can not be null");
        SAXReader reader = new SAXReader();
        Document document = reader.read(this.url);
        this.rootElement = document.getRootElement();
        return document;
    }
    public Document parseByPath(){
        Assert.isTrue(this.path!=null, "path can not be null");
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(this.path);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        this.rootElement = document.getRootElement();
        return document;
    }
    private void getNodes(Element node) {
        //递归遍历当前节点所有的子节点
        List<Element> listElement = node.elements();
        for (Element e : listElement) {
            this.elements.add(e);
            this.map.put(e.getName(), e.getData());
            this.getNodes(e);
        }
    }
    public List<Element> getElements(){
        this.elements = new ArrayList<>();
        getNodes(this.rootElement);
        return elements;
    }
    public Map<String, Object> getElementMap(){
        this.map = new HashMap<>();
        getNodes(this.rootElement);
        return this.map;
    }
}

再编写一个dos命令执行类。

package com.regedit;

import org.springframework.util.Assert;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lucas
 * exec win command
 */
public class WindowsRegistry {

    private String command;
    private List<String> commands;
    public WindowsRegistry(String command){
        this.command = command;
    }
    public WindowsRegistry(List<String> commands){
        this.commands = commands;
    }
    /**
     * @Description do windows command
     * @Param command
     * @return GBK resulet byte[]
     **/
    public byte[] doCommand() throws Exception{
        Assert.isTrue(command != null, "command can not be empty");
        StreamReader reader = new StreamReader(this.command);
        reader.start();
        reader.join();
        return reader.getResult();
    }
    public Map<String, byte[]> doListCommand() throws Exception{
        Assert.isTrue(this.commands != null, "commands can not be empty");
        Map<String, byte[]> map = new HashMap<>();
        for (String command : commands) {
            StreamReader reader = new StreamReader(command);
            reader.start();
            reader.join();
            map.put(command, reader.getResult());
        }
        return map;
    }
    static class StreamReader extends Thread {
        private String command;
        private byte[] bytes;
        public StreamReader(String command) {
            this.command = command;
        }
        @Override
        public void run() {
            try {
                Process process = Runtime.getRuntime().exec(command);
                process.waitFor();
                bytes = toByteArray(process.getInputStream());
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e2){
                throw new RuntimeException(e2);
            }
        }
        public byte[] getResult() {
            return bytes;
        }
        public String getCommand() {
            return command;
        }
    }
    private static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*4];
        int n;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
}

解耦实现添加注册表的一个类。

package com.regedit;
import org.springframework.data.util.CastUtils;
/**
 * @version V1.0
 */
public class AddRegistryCommand extends RegistryCommand{
    public AddRegistryCommand(String path, String valuNameCommand,
                                    String valueName, String valueTypeCommand, String valueType,
                                        String valueCommand, String value, boolean override){
        this.commandHead = RegistryCommandContants.ADD_COMMAND;
        this.path = path;
        this.valuNameCommand = valuNameCommand;
        this.valueName = valueName;
        this.valueTypeCommand = valueTypeCommand;
        this.valueType = valueType;
        this.valueCommand = valueCommand;
        this.value = value;
        this.override = override;
    }
    public AddRegistryCommand(String path, String valuNameCommand,
                              String valueName, String valueTypeCommand, String valueType,
                              String valueCommand, String value){
        this.commandHead = RegistryCommandContants.ADD_COMMAND;
        this.path = path;
        this.valuNameCommand = valuNameCommand;
        this.valueName = valueName;
        this.valueTypeCommand = valueTypeCommand;
        this.valueType = valueType;
        this.valueCommand = valueCommand;
        this.value = value;
        this.override = true;
    }
    public AddRegistryCommand(String path, String valueName, Object value){
        this.commandHead = RegistryCommandContants.ADD_COMMAND;
        this.path = path;
        this.valuNameCommand = RegistryCommandContants.CONSTANT_V;
        this.valueName = valueName;
        this.valueCommand = RegistryCommandContants.CONSTANT_D;
        if (value !=null ) {
            if (value instanceof String) {
                this.valueTypeCommand = null;
                this.valueType = null;
                this.value = String.valueOf(value);
            } else if (value instanceof Integer) {
                this.valueTypeCommand = null;
                this.valueType = null;
                this.value = String.valueOf(value);
            } else {
                throw new UnsupportedTypeException("the value type is unsupported");
            }
        }
        this.override = true;
    }
    public AddRegistryCommand(String path, String valuNameCommand,
                              String valueName,String valueCommand, Object value, boolean override){
        this.commandHead = RegistryCommandContants.ADD_COMMAND;
        this.path = path;
        this.valuNameCommand = valuNameCommand;
        this.valueName = valueName;
        this.valueCommand = valueCommand;
        if (value !=null ) {
            if (value instanceof String) {
                this.valueTypeCommand = null;
                this.valueType = null;
                this.value = CastUtils.cast(value);
            } else if (value instanceof Integer) {
                this.valueTypeCommand = null;
                this.valueType = null;
                this.value = CastUtils.cast(value);
            } else {
                throw new UnsupportedTypeException("the value type is unsupported");
            }
        }
        this.override = true;
    }
    public class UnsupportedTypeException extends RuntimeException {
        static final long serialVersionUID = -1242599979055084673L;
        public UnsupportedTypeException() {
        }
        public UnsupportedTypeException(String message) {
            super(message);
        }
        public UnsupportedTypeException(String message, Throwable cause) {
            super(message, cause);
        }
        public UnsupportedTypeException(Throwable cause) {
            super(cause);
        }
    }
}

注册表命令类父类。

package com.regedit;

import org.springframework.util.Assert;

/**
 * @author lucas
 * reg command is support add/delete/query and more
 * @version V1.0
 */
public class RegistryCommand extends Command {
    protected String commandHead;
    protected String path;
    protected String valuNameCommand;
    protected String valueName;
    protected String valueTypeCommand;
    protected String valueType;
    protected String valueCommand;
    protected String value;
    protected boolean override;
    public final String getConmand(){
        Assert.isTrue(this.commandHead != null,"command head can not be empty");
        Assert.isTrue(this.path != null,"path head can not be empty");
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(this.commandHead).append(this.path);
        if ( this.valuNameCommand != null ) {
            stringBuffer.append(this.valuNameCommand).append(this.valueName);
        }
        if ( this.valueTypeCommand != null ) {
            stringBuffer.append(this.valueTypeCommand).append(this.valueType);
        }
        if ( this.valueCommand != null ) {
            stringBuffer.append(this.valueCommand).append(this.value);
        }
        if (this.override) {
            stringBuffer.append( " /f ");
        }
        return stringBuffer.toString();
    }
}

父类做一个控制。

package com.regedit;
import org.springframework.util.Assert;
/**
 * @version V1.0
 */
public class Command {
    private String command;
    private String getCommand(){
        Assert.isTrue(command != null, "command can not be empty");
        return this.command;
    }

}

转换工具类

package com.util;

import org.springframework.data.util.CastUtils;

import java.util.Map;
import java.util.Set;

/**
 * <p>TransformUtils</p>
 * @version V1.0
 */
public class TransformUtils {
    public static Map<String, Object> objectMap2TypeMap(Map<String, Object> map){
        Set<Map.Entry<String, Object>> sets = map.entrySet();
        for (Map.Entry<String, Object> e : sets) {
            e.setValue(object2Intobj(e.getValue()));
        }
        return map;
    }
    public static Object object2Intobj(Object o){
        if (isCreatable(CastUtils.cast(o))) {
            return Integer.parseInt(CastUtils.cast(o));
        }
        return o;
    }
    public static boolean isCreatable(String str) {
        if ( isEmpty(str) ) {
            return false;
        } else {
            char[] chars = str.toCharArray();
            int sz = chars.length;
            boolean hasExp = false;
            boolean hasDecPoint = false;
            boolean allowSigns = false;
            boolean foundDigit = false;
            int start = chars[0] != '-' && chars[0] != '+' ? 0 : 1;
            int i;
            if (sz > start + 1 && chars[start] == '0' && !contains(str, 46)) {
                if (chars[start + 1] == 'x' || chars[start + 1] == 'X') {
                    i = start + 2;
                    if (i == sz) {
                        return false;
                    }
                    while(i < chars.length) {
                        if ((chars[i] < '0' || chars[i] > '9') && (chars[i] < 'a' || chars[i] > 'f') && (chars[i] < 'A' || chars[i] > 'F')) {
                            return false;
                        }
                        ++i;
                    }
                    return true;
                }
                if (Character.isDigit(chars[start + 1])) {
                    for(i = start + 1; i < chars.length; ++i) {
                        if (chars[i] < '0' || chars[i] > '7') {
                            return false;
                        }
                    }
                    return true;
                }
            }
            --sz;
            for(i = start; i < sz || i < sz + 1 && allowSigns && !foundDigit; ++i) {
                if (chars[i] >= '0' && chars[i] <= '9') {
                    foundDigit = true;
                    allowSigns = false;
                } else if (chars[i] == '.') {
                    if (hasDecPoint || hasExp) {
                        return false;
                    }
                    hasDecPoint = true;
                } else if (chars[i] != 'e' && chars[i] != 'E') {
                    if (chars[i] != '+' && chars[i] != '-') {
                        return false;
                    }
                    if (!allowSigns) {
                        return false;
                    }
                    allowSigns = false;
                    foundDigit = false;
                } else {
                    if (hasExp) {
                        return false;
                    }
                    if (!foundDigit) {
                        return false;
                    }
                    hasExp = true;
                    allowSigns = true;
                }
            }
            if (i < chars.length) {
                if (chars[i] >= '0' && chars[i] <= '9') {
                    return true;
                } else if (chars[i] != 'e' && chars[i] != 'E') {
                    if (chars[i] == '.') {
                        return !hasDecPoint && !hasExp ? foundDigit : false;
                    } else if (!allowSigns && (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F')) {
                        return foundDigit;
                    } else if (chars[i] != 'l' && chars[i] != 'L') {
                        return false;
                    } else {
                        return foundDigit && !hasExp && !hasDecPoint;
                    }
                } else {
                    return false;
                }
            } else {
                return !allowSigns && foundDigit;
            }
        }
    }
    public static boolean contains(CharSequence seq, int searchChar) {
        if (isEmpty(seq)) {
            return false;
        } else {
            return indexOf(seq, searchChar, 0) >= 0;
        }
    }
    static int indexOf(CharSequence cs, int searchChar, int start) {
        if (cs instanceof String) {
            return ((String)cs).indexOf(searchChar, start);
        } else {
            int sz = cs.length();
            if (start < 0) {
                start = 0;
            }
            if (searchChar < 65536) {
                for(int i = start; i < sz; ++i) {
                    if (cs.charAt(i) == searchChar) {
                        return i;
                    }
                }
            }
            if (searchChar <= 1114111) {
                char[] chars = Character.toChars(searchChar);

                for(int i = start; i < sz - 1; ++i) {
                    char high = cs.charAt(i);
                    char low = cs.charAt(i + 1);
                    if (high == chars[0] && low == chars[1]) {
                        return i;
                    }
                }
            }
            return -1;
        }
    }
    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }
}

测试代码

package com.testpackage;

import com.reader.xml.XmlReader;
import com.regedit.AddRegistryCommand;
import com.regedit.WindowsRegistry;
import com.util.TransformUtils;
import org.apache.commons.collections.bag.SynchronizedSortedBag;

import java.util.*;

/**
 * <p>XmlTest</p>
 *
 * @author wangjiajia12 2019/8/20 16:46
 * @version V1.0
 */
public class XmlTest {

    public static void main(String[] args){
        XmlReader xmlReader = new XmlReader("D:\\00csv\\sfrzcfg");
        Map<String, Object> map = xmlReader.getElementMap();
        map = TransformUtils.objectMap2TypeMap(map);
        Set<Map.Entry<String, Object>> sets = map.entrySet();
        List<String> commands = new ArrayList<>();
        for (Map.Entry<String, Object> e : sets) {
            AddRegistryCommand command = new AddRegistryCommand("HKEY_LOCAL_MACHINE\\SOFTWARE\\Client\\YH", e.getKey(), e.getValue());
            commands.add(command.getConmand());
        }
        WindowsRegistry registrys = new WindowsRegistry(commands);
        WindowsRegistry registry = new WindowsRegistry(commands.get(0));
        try {
            byte[] b = registry.doCommand();
            System.out.println(new String(b, "GBK"));
            Map<String, byte[]> result = registrys.doListCommand();
            Map<String, String> records = new HashMap<>();
            for (Map.Entry<String, byte[]> e :  result.entrySet()) {
                String s = new String(e.getValue(), "GBK");
                records.put(e.getKey(), new String(e.getValue(), "GBK"));
            }
            System.out.println(records);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

测试结果

操作成功完成。

{REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Client\YH /v HN /d 2 /f =操作成功完成。
, REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Client\YH /v SCN /d 0 /f =操作成功完成。
, REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Client\YH /v LEN /d 2 /f =操作成功完成。
, REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Client\YH /v KR /d UqknrfHqnydqdjra /f =操作成功完成。
, REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Client\YH /v TYP /d 0 /f =操作成功完成。
, REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Client\YH /v RN /d 0 /f =操作成功完成。
, REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Client\YH /v HT /d 6ee837327883701449e65c41af3538d14da65465f4046c1bae4c22a90e8c35f73849e32c936598baa9bfe7bba2d49885ee4c5fa1e8d57e361a162e97c62143c4 /f =操作成功完成。
, REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Client\YH /v PD /d 0 /f =操作成功完成。
, REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Client\YH /v PARAM /d pX3nftWedUAe8ngi /f =操作成功完成。
, REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Client\YH /v MOD /d 0 /f =操作成功完成。
}

通过一个简单的例子实现了windows命令及结果实现的获取,以及xml简单的读取。为了更多的命令实现,可以进行控制及解耦操作,工作之余写了个简单的demo,如各位有借鉴之处,还请注明出处,感谢。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值