一、读取yaml文件
<dependency>
<groupId>org.jyaml</groupId>
<artifactId>jyaml</artifactId>
<version>1.3</version>
</dependency>
import org.ho.yaml.Yaml;
private void loadThreshold(){
Yaml yaml = new Yaml();
try{
InputStream is = this.getClass().getClassLoader().getResourceAsStream("threshold.yaml");
Map<String, Map<String, Object>> fileMap = (HashMap<String, Map<String, Object>>)yaml.load(is);
for(Map.Entry<String, Map<String, Object>> entry : fileMap.entrySet()){
metrics.add(entry.getKey());
Map<String, Object> map = entry.getValue();
String name = (String)map.get("name");
double threshold_warning = (Double)map.get("threshold_warning");
double threshold_downgrade = (Double)map.get("threshold_downgrade");
Threshold threshold = new Threshold(name, threshold_warning, threshold_downgrade);
thresholdMap.put(entry.getKey(), threshold);
}
LOGGER.info("loading threhold file is successful.");
}catch(Exception e){
LOGGER.error("loading threshold file failed.");
}
}
二、读取文本文件
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.io.FileUtils;
public static List<String> loadFile(String file) {
List<String> keyword = new ArrayList<String>();
//这个方法只适用于调试时使用,打包后运行jar会找不到文件
String path = "src//main//resources//" + file;
try {
LineIterator uidLineIterator = FileUtils.lineIterator(new File(path));
while (uidLineIterator.hasNext()) {
String line = uidLineIterator.nextLine();
keyword.add(line);
}
}catch(Exception e) {
e.printStackTrace();
}
return keyword;
}
三、写文本文件
import java.io.FileOutputStream;
FileOutputStream fos = new FileOutputStream("/Users/bruce/Documents/uid2.txt", false);
for(String s : list){
String str = s + "\n";
byte[] by = str.getBytes();
fos.write(by, 0, by.length);
}
// FileOutputStream第二个参数true/false表示是否追加到文件末尾。
四、storm任务加载配置文件
配置文件(注意转义)
12345\:province_11=1
12345\:province_12=2
12345\:city_0001=4
12345\:city_0002=3
12345\:city_0003=3
代码
import java.util.Properties;
public class LoadProperties {
private static Properties cityMap;
static{
cityMap = new Properties();
try{
cityMap.load(LoadProperties.class.getClassLoader().getResourceAsStream("file.properties"));
}catch (Exception e){
e.printStackTrace();
}
}
public static String getCity(String code) {
return cityMap.getProperty(code);
}
}