22 august 2017

Property value reader example / Java

# Settings for starting Matlab in stay-alive mode
matlab_path=C:/Users/Me/Desktop/backend
matlab_exe_filename=lev_lis_interface_main.exe
matlab_exe_params=standard log.txt logs


-------------

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** * Created by Me on 8/22/2017. */public class MatlabPropertyValues {

    private static final Logger LOGGER = LoggerFactory.getLogger(MatlabPropertyValues.class);

    private String executablePath;
    private String executableName;
    private String executableParams;

    InputStream inputStream = null;

    private static MatlabPropertyValues instance = null;

    public static MatlabPropertyValues getInstance() {
        if (instance == null) {
            instance = new MatlabPropertyValues();
            instance.loadPropValues();
        }
        return instance;
    }

    private void loadPropValues() {
        try {
            Properties prop = new Properties();
            String propFileName = "config.properties";

            inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);  // may be different

            if (inputStream != null) {
                prop.load(inputStream);
            } else {
                throw new FileNotFoundException("Property file '" + propFileName + "' not found in the classpath");
            }

            executablePath = prop.getProperty("matlab_path");
            executableName = prop.getProperty("matlab_exe_filename");
            executableParams = prop.getProperty("matlab_exe_params");

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        } finally {
            try {
                inputStream.close();
            }
            catch (IOException e) {
                e.printStackTrace();
                LOGGER.error(e.getMessage());
            }
        }
    }

    public String getExecutablePath() {
        return executablePath;
    }

    public String getExecutableName() {
        return executableName;
    }

    public String getExecutableParams() {
        return executableParams;
    }

    public static List<String> getPropertyValuesAsList() {
        List<String> args = new ArrayList<>();
        MatlabPropertyValues instance = getInstance();
        args.add(instance.getExecutablePath());
        args.add(instance.getExecutablePath() + "\\" + instance.getExecutableName());
        String params [] = instance.getExecutableParams().split(" ");
        args.add(params[0] + " " + (instance.getExecutablePath() + "\\" + params[1]) + " " +
                (instance.getExecutablePath() + "\\" + params[2]));
        return args;
    }
}

Niciun comentariu: