在打包jar包中,和本地运行都没有问题
我本地的位置是
服务器的位置是
package com.ktamr.common.utils;
import java.io.*;
import java.util.Properties;
/**
* 属性文件的IO操作
* @author by小可爱
*
*/
public class PropertiesUtil {
private static String properiesName = "config/user.properties";
public PropertiesUtil() {
}
public PropertiesUtil(String fileName) {
this.properiesName = fileName;
}
/**
* 按key获取值
* @param key
* @return
*/
public static String readProperty(String key) {
String value = "";
InputStream is = null;
try {
try {
is = new FileInputStream(properiesName);
} catch (Exception e) {
is = PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);
}
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
Properties p = new Properties();
p.load(br);
value = p.getProperty(key);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return value;
}
/**
* 获取整个配置信息
* @return
*/
public static Properties getProperties() {
Properties p = new Properties();
InputStream is = null;
try {
try {
is = new FileInputStream(properiesName);
} catch (Exception e) {
is = PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);
}
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
p.load(br);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return p;
}
/**
* key-value写入配置文件
* @param key
* @param value
*/
public static void writeProperty(String key, String value) {
InputStream is = null;
OutputStream os = null;
Properties p = new Properties();
try {
try {
//本地文件位置
is = PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);
os = new FileOutputStream(PropertiesUtil.class.getClassLoader().getResource(properiesName).getFile());
} catch (Exception e) {
//如果报错就是文件未找到,服务器的位置
is = new FileInputStream(properiesName);
os = new FileOutputStream(properiesName);
}
System.out.println();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
p.load(br);
System.out.println();
p.setProperty(key, value);
p.store(os, key);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is)
is.close();
if (null != os)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}