Read and update properties configuration file (support Chinese)

    First, modify the properties configuration file to be operated into UTF-8 encoding
	// Get the property value of the properties file
	public static String readPropertiesFile(String filePath, String key) throws FileNotFoundException, IOException {
		try {
			Properties props = new Properties();
			props.load(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
			String value = props.getProperty(key);
			System.out.println(key + "The value of the key is: " + value);
			return value;
		} catch (Exception e) {
			e.printStackTrace ();
			return null;
		}
	}

	/**
	 * Update (or insert) a pair of properties information (primary key and its key value) If the primary key already exists, update the value of the primary key; if the primary key does not exist, the plugin will add a pair of key values.
	 *
	 * @param key
	 * key name
	 * @param value
	 * key value
	 */
	public static void writePropertiesFile(String filePath, String key, String value) throws IOException {
		Properties properties = new Properties();
		File file = new File(filePath);
		FileInputStream fis = new FileInputStream(file);
		properties.load(new InputStreamReader(new FileInputStream(file),"UTF-8"));
		// You must use map to save all the content first, otherwise the original content will be gone when updated
		Map<String, String> map = new HashMap<String, String>();
		Set<Object> keySet = properties.keySet();
		for (Object object : keySet) {
			String keytmp = (String) object;
			String valuetmp = (String) properties.getProperty(keytmp);
			System.out.println(keytmp + "=" + valuetmp);
			map.put(keytmp, valuetmp);
		}
		map.put(key, value);
		for (java.util.Map.Entry<String, String> entry : map.entrySet()) {
			properties.setProperty(entry.getKey(), entry.getValue());
		}
		FileOutputStream fos = new FileOutputStream(file);
		properties.store(new OutputStreamWriter(fos), "update");
		fos.close();
		fis.close();
	}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326355537&siteId=291194637