本示例的应用场景:
读取模板文件夹的模板文件,然后替换占位符,生成指定文件到指定文件夹。
由于不同用户有不同的地址,所以需要在配置文件中编辑属于自己的两个地址
项目地址:ProjectPath
模板地址:FtlPath
配置文件地址:filePath
配置文件放在项目WorkSpace下,导出jar后可以放置在jar包同级目录
示例内容如下:
#项目地址
ProjectPath=D:/WorkSpace/project
#模板地址
FtlPath=D:/WorkSpace
代码如下:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.File;
public class testIO {
public static void main(String[] args) {
String ProjectPath = null;
String FtlPath = null;
String filePath = System.getProperty("user.dir")
+ "\\filePath.txt";
try {
String encoding = "GBK";
File file = new File(filePath);
System.out.println("filePath"+filePath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
if ("#".equals(lineTxt.substring(0, 1))) {
} else {
if ("P".equals(lineTxt.substring(0, 1))) {
ProjectPath = lineTxt.substring(12,
lineTxt.length());
System.out.println("ProjectPath:"+ProjectPath);
} else if ("F".equals(lineTxt.substring(0, 1))) {
FtlPath = System.getProperty("user.dir") + "/ftl/";
System.out.println("FtlPath"+FtlPath);
}
}
}
read.close();
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
}
}
String filePath = System.getProperty("user.dir") + "\\filePath.txt";
System.getProperty("user.dir") 获取程序的位置,加上文件名filePath.txt 即为配置文件地址
while循环中,每次读取一行,若是#开头的则不做任何处理,直接读取下一行
接下来判断开头是ProjectPath还是FtlPath,分别存到各自变量中
当中存在编码问题也用InputStreamReader时设置了编码,所以不会出现中文乱码问题