Java排序Properties OrderedProperties getClassLocation getWorkDir getLineSeparator getCurDir

2015-12-06 21:46:00
admin
原创 1718
摘要:Java排序Properties OrderedProperties getClassLocation getWorkDir getLineSeparator getCurDir

一、实用类简介

OrderedProperties类:

java.util.Properties类没有按属性排列的顺序进行排序,补充此类用于某些场景。


Common类,提供一些实用方法:

getClassLocation 获取class路径,jar文件内的class路径也可以获取。

getWorkDir 获取class路径,兼容调试bin路径。

getLineSeparator 获取行分隔符。

getCurDir 获取当前工作目录。

loadProperties 加载properties文件。

saveProperties 存储properties文件。


二、代码下载和代码片段

下载地址:OrderedProperties.java Common.java

package common;

import java.io.*;
import java.net.*;
import java.util.*;

public class Common {

@SuppressWarnings("rawtypes")
public static String getClassLocation(Class cls) {
URL url = cls.getProtectionDomain().getCodeSource().getLocation();
String filePath = null;
try {
filePath = URLDecoder.decode(url.getPath(), "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
if (filePath.endsWith(".jar")) {
filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
}
return new File(filePath).getAbsolutePath();
}

@SuppressWarnings("rawtypes")
public static String getWorkDir(Class cls) {
String bin = "bin";
String workDir = getClassLocation(cls);
if (workDir.endsWith(bin)) {
workDir = workDir.substring(0, workDir.length() - bin.length());
workDir = new File(workDir).getAbsolutePath();
}
return workDir;
}

public static String getLineSeparator() {
return System.getProperty("line.separator");
}

public static String getCurDir() {
return System.getProperty("user.dir");
}

public static Properties loadProperties(String filename) {
Properties properties = new OrderedProperties();
try {
FileInputStream input = new FileInputStream(filename);
properties.load(input);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return properties;
}

public static void saveProperties(Properties properties, String filename, String comments) throws IOException {
try {
File file = new File(filename);
file.createNewFile();
FileOutputStream output = new FileOutputStream(file);
properties.store(output, comments);
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
System.out.println(getWorkDir(Common.class));
}
}

发表评论
评论通过审核之后才会显示。