2 回答
TA贡献1843条经验 获得超7个赞
其实很简单的
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class CfgWriter {
private PrintWriter out;
private static final String DEFINE = "define";
public CfgWriter(File file) throws FileNotFoundException {
super();
this.out = new PrintWriter(file);
}
public void writeComment(String comment) {
out.print('#');
out.println(comment);
}
public void startDefine(String name) {
out.print(DEFINE);
out.print(' ');
out.print(name);
out.println('{');
}
public void writeProperty(String key, String value) {
out.print(' ');
out.print(key);
out.print('\t');
out.println(value);
}
public void endDefine() {
out.println('}');
}
public void close() {
out.close();
}
public static void main(String[] args) throws Exception {
CfgWriter w = new CfgWriter(new File("d:/config.cfg"));
w.writeComment("config.cfg");
w.startDefine("Server");
w.writeProperty("Id", "0001");
w.writeProperty("Name", "xxxx");
w.writeProperty("Amount", "100");
w.endDefine();
w.close();
}
}
TA贡献1921条经验 获得超9个赞
方法有好多,最直接的就是自己控制字符串的格式来写文件,就是复杂了点。
比较好的可以用模板引擎,如freemarker、velocity什么的,生成字符串再写文件。
添加回答
举报