【发布时间】:2014-05-10 00:27:56
【问题描述】:
我编写了下面的代码来检查属性文件是否存在并具有所需的属性。如果存在,则打印文件存在且完好无损的消息,如果不存在,则创建具有所需属性的属性文件。
我想知道的是,是否有更优雅的方式来做到这一点,或者我的方式几乎是最好的方式?另外我遇到的一个小问题是,通过这种方式它不会检查不应该存在的额外属性,有没有办法做到这一点?
我的要求总结:
- 检查文件是否存在
- 检查它是否具有所需的属性
- 检查它是否有额外的属性
- 如果文件不存在或者有额外或缺失的属性,请创建具有所需属性的文件
Source files and Netbeans Project download
来源:
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 TestClass {
public static void main(String[] args) {
File propertiesFile = new File("config.properties");
if (propertiesFile.exists() && propertiesExist(propertiesFile)) {
System.out.println("Properties file was found and is intact");
} else {
System.out.println("Properties file is being created");
createProperties(propertiesFile);
System.out.println("Properties was created!");
}
}
public static boolean propertiesExist(File propertiesFile) {
Properties prop = new Properties();
InputStream input = null;
boolean exists = false;
try {
input = new FileInputStream(propertiesFile);
prop.load(input);
exists = prop.getProperty("user") != null
&& prop.getProperty("pass") != null;
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return exists;
}
public static void createProperties(File propertiesFile)
{
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream(propertiesFile);
prop.setProperty("user", "username");
prop.setProperty("pass", "password");
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
【问题讨论】:
标签: java file fileinputstream fileoutputstream properties-file