日期:2014-05-17  浏览次数:20729 次

this.getClass().getResourceAsStream("src/test.properties")为什么null值
本帖最后由 Gemerl 于 2014-01-12 16:59:58 编辑

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public class Util {

/**
 * @param args
 */
public static void main(String[] args) {
new Util().writeProperties();
}

public void writeProperties(){
Properties p = new Properties();
p.setProperty("name","Gemerl");
p.setProperty("password","123456");
File file=new File("src/properties");
InputStream in;
OutputStream os;
if(!file.exists()){
file.mkdirs();
}
file=new File("src/properties/test.properties");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
in = new BufferedInputStream(new FileInputStream(file));
p.load(in);
os = new FileOutputStream(file);
p.store(os, "看能写注释不..");
in.close();
os.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
/**
 * 
 * @return 通过properties的key返回value值
 */
public String getString(String key){
InputStream in = this.getClass().getResourceAsStream("src/test.properties");
                //上面的这句in是null值
Properties props = new Properties();
String val=null;
try {
props.load(in);
val=(String) props.getProperty(key);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return val;
}
}

文件结构




File file=new File("src/properties");
if(!file.exists()){
file.mkdirs();
}
file=new File("src/properties/test.properties");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


另外,如果我想让properties文件不存在就自动在src下面创建该怎么写的。。