/**
	 * @Description 测试
	 */
	public static void main(String[] args) {
		try {
			getFilePath("A:\\210530\\test.properties");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param path 文件路径
	 * @return
	 */
	public static void getFilePath(String path) throws Exception {
		File file = new File(path);
		// 读取
		PropertiesUtil p = PropertiesUtil.readOrderedPropertiesFile(file.getPath());
		Enumeration<?> enumeration = p.keys();
		while (enumeration.hasMoreElements()) {// 打印内容
			Object o = enumeration.nextElement();
			System.out.println("key=" + o.toString() + ",value=" + p.getProperty(o.toString()));
		}
		p.firstPut("title", "first line");// 在前面插入
		p.remove("test");// 删除key=test的行
		p.writeOrderedPropertiesFile(file.getPath(), false);// 重新写入
	}

 

package com.cy;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

/**
 * @Package: com.chenyu.demo.utils
 * @ClassName: PropertiesUtil
 * @Author: Cy
 * @Description: 读写Properties工具类
 * @Date: 2021-5-04 15:55
 * @Version: 2.0
 */
public final class PropertiesUtil extends Properties {

	private static final long serialVersionUID = 4175783799452215304L;

	private List<Object> keyList = new ArrayList();

	/**
	 * 默认构造方法
	 */
	PropertiesUtil() {
	}

	/**
	 * 从指定路径加载信息到Properties
	 * 
	 * @param path
	 */
	public PropertiesUtil(String path) {
		try {
			InputStream is = new FileInputStream(path);
			this.load(is);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException("file does not exist ");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @author Cy
	 * @date 2021年6月1日 上午11:27:30
	 * @Description 把所有内容去空格首字母大写
	 * @parameter
	 * @return
	 */
	public void partitionFirstToUpper() {
		String val = "";
		for (int i = 0; i < keyList.size(); i++) {
			String[] arr = get(i).toString().split(" ");
			val = "";
			for (int j = 0; j < arr.length; j++) {
				val += StringTest.upperFirstLatter(arr[j]);
			}
			super.put(keyList.get(i), val);
		}
	}

	/**
	 * @author Cy
	 * @date 2021年4月29日 上午9:33:12
	 * @Description 插入到最前面
	 * @parameter key:value
	 * @return
	 */
	public synchronized Object firstPut(Object key, Object value) {
		this.removeKeyIfExists(key);
		keyList.add(0, key);
		return super.put(key, null == value ? "" : value);
	}

	/**
	 * @author Cy
	 * @date 2021年5月29日 上午9:33:12
	 * @Description 重写put方法,插入指定位置
	 * @parameter key:value
	 * @return
	 */
	public synchronized Object put(Object key, Object value, Integer index) {
		this.removeKeyIfExists(key);
		keyList.add(index, key);
		return super.put(key, null == value ? "" : value);
	}

	/**
	 * @author Cy
	 * @date 2021年5月29日 上午9:33:12
	 * @Description 重写put方法,按照property的存入顺序保存key到keyList,遇到重复的后者将覆盖前者。
	 * @parameter key:value
	 * @return
	 */
	@Override
	public synchronized Object put(Object key, Object value) {
		this.removeKeyIfExists(key);
		keyList.add(key);
		return super.put(key, null == value ? "" : value);
	}

	/**
	 * @author Cy
	 * @param Object
	 * @date 2021年5月25日 上午11:50:12
	 * @Description 重写remove方法,删除属性时清除keyList中对应的key。
	 * @parameter key
	 * @return
	 */
	public synchronized Object remove(Object key) {
		this.removeKeyIfExists(key);
		if (keyList.contains(key)) {
			keyList.remove(key);
		}
		return super.remove(key);
	}

	/**
	 * keyList中存在指定的key时则将其删除
	 */
	private void removeKeyIfExists(Object key) {
		keyList.remove(key);
	}

	public List<Object> getKeyList() {
		return this.keyList;
	}

	void setKeyList(List<Object> keys1) {
		this.keyList = keys1;
	}

	/**
	 * 保存Properties到指定文件,默认使用UTF-8编码
	 * 
	 * @param path 指定文件路径
	 */
	public void store(String path) throws IOException {
		this.store(path, "UTF-8", false);
	}

	/**
	 * 重写keys方法,返回根据keyList适配的Enumeration,且保持HashTable keys()方法的原有语义,
	 * 每次都调用返回一个新的Enumeration对象,且和之前的不产生冲突
	 */
	@Override
	public synchronized Enumeration<Object> keys() {
		return new EnumerationAdapter<Object>(keyList);
	}

	/**
	 * List到Enumeration的适配器
	 */
	private class EnumerationAdapter<T> implements Enumeration<T> {
		private int index = 0;
		private final List<T> list;
		private final boolean isEmpty;

		public EnumerationAdapter(List<T> list) {
			this.list = list;
			this.isEmpty = list.isEmpty();
		}

		public boolean hasMoreElements() {
			// isEmpty的引入是为了更贴近HashTable原有的语义,在HashTable中添加元素前调用其keys()方法获得一个Enumeration的引用,
			// 之后往HashTable中添加数据后,调用之前获取到的Enumeration的hasMoreElements()将返回false,但如果此时重新获取一个
			// Enumeration的引用,则新Enumeration的hasMoreElements()将返回true,而且之后对HashTable数据的增、删、改都是可以在
			// nextElement中获取到的。
			return !isEmpty && index < list.size();
		}

		public T nextElement() {
			if (this.hasMoreElements()) {
				return list.get(index++);
			}
			return null;
		}

	}

	/**
	 * @author Cy
	 * @date 2021年5月30日 上午10:04:09
	 * @Description 按顺序读Properties文件
	 * @parameter [properties,路径,是否追加]
	 * @return
	 */
	public static PropertiesUtil readOrderedPropertiesFile(String path) {
		PropertiesUtil properties = new PropertiesUtil();
		InputStreamReader inputStreamReader = null;
		try {
			InputStream inputStream = new BufferedInputStream(new FileInputStream(path));
			// prop.load(inputStream);
			inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			properties.load(inputStreamReader);
		} catch (Exception e) {
			System.err.println(e.getMessage());
		} finally {
			if (null != inputStreamReader) {
				try {
					inputStreamReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return properties;
	}

	/**
	 * @author Cy
	 * @date 2021年5月30日 上午10:04:09
	 * @Description 按顺序写Properties文件
	 * @parameter [properties,路径,是否追加]
	 * @return
	 */
	public static void writeOrderedPropertiesFile(PropertiesUtil properties, String path, boolean append)
			throws IOException {
		properties.store(path, "utf-8", append);
	}

	/**
	 * @author Cy
	 * @date 2021年6月1日 下午2:49:47
	 * @Description保存Properties到指定文件,并指定对应存放编码
	 * @param path    指定路径
	 * @param charset 文件编码
	 * @param append  是否追加
	 * @return
	 */
	public void store(String path, String charset, boolean append) throws IOException {
		if (path != null && !"".equals(path)) {
			BufferedWriter bw = null;
			try {
				OutputStream os = new FileOutputStream(path, append);
				bw = new BufferedWriter(new OutputStreamWriter(os, charset));
				this.store(bw, null);

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (null != bw) {
					bw.close();
				}
			}
		} else {
			throw new RuntimeException("The path is invalid");
		}
	}

	@Override
	public String toString() {
		String result = "";
		StringBuffer s = new StringBuffer("");
		int r = 0;
		for (; r < keyList.size(); r++)
			s.append(keyList.get(r).toString()).append("=").append(super.defaults.get(keyList.get(r).toString()))
					.append("\n");
		return result;
	}

	/**
	 * implements List
	 */

	public boolean add(Object e, Object value) {
		int hash = value.hashCode();
		this.removeKeyIfExists(hash);
		keyList.add(e);
		return null != super.put(hash, null == value ? "" : value);
	}

	public boolean addAll(Collection c) {
		Object[] a = c.toArray();
		int numNew = a.length;
		System.arraycopy(a, 0, keyList, keyList.size(), numNew);
		return numNew != 0;
	}

	public boolean addAll(int index, Collection c) {
		Object[] a = c.toArray();
		int numNew = a.length;
		System.arraycopy(a, index, keyList, index, numNew);
		return numNew != 0;
	}

	public boolean removeAll(Collection c) {
		Objects.requireNonNull(c);
		int r = 0;
		for (; r < keyList.size(); r++)
			if (c.contains(keyList.get(r)))
				remove(keyList.get(r));
		return c.size() != 0;
	}

	public Object get(int index) {
		return this.getProperty(keyList.get(index).toString());
	}

	public Object set(int index, Object element) {
		keyList.set(index, element);
		return null != super.put(element.hashCode(), element);
	}

	public void add(int index, Object element) {
		int hash = element.hashCode();
		this.removeKeyIfExists(hash);
		keyList.set(index, element);
		super.put(hash, null == element ? "" : element);

	}

	public Object remove(int index) {
		super.remove(keyList.get(index));
		return keyList.remove(index);
	}

	public Object indexOfValue(Object o) {
		int r = 0;
		for (; r < keyList.size(); r++)
			if (o == super.defaults.getProperty(keyList.get(r).toString()))
				return keyList.get(r);
		return null;
	}

	public int lastIndexOf(Object o) {
		int r = keyList.size();
		if (o == null) {
			for (int i = r - 1; i >= 0; i--)
				if (keyList.get(i) == null)
					return i;
		} else {
			for (int i = r - 1; i >= 0; i--)
				if (o.equals(keyList.get(i)))
					return i;
		}
		return -1;
	}
}

 

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐