问题描述
例如:#config.cfg define server{ userName xiaoming hostName window alias XP hostIP 192.168.1.1 } define client{ userName changchun hostName Linux alias ubuntu hostIP 192.168.1.2} define server{ userName xiaoming1 hostName window alias XP1 hostIP 192.168.1.3 } define client{ userName changchun1 hostName Linux alias ubuntu1 hostIP 192.168.1.4}......
解决方案
其实很简单的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();}}
解决方案二:
不错,学习!
解决方案三:
方法有好多,最直接的就是自己控制字符串的格式来写文件,就是复杂了点。比较好的可以用模板引擎,如freemarker、velocity什么的,生成字符串再写文件。