最近在开发代码生成器的时候,需要读取模版文件,根据模板替换相应的字符,然后输出所期望的类,因为在java或者C++里面没有直接支持替换的功能,因此在实现模板字符替换的时候,需要编写一定的代码实现替换功能。对模板文件的操作,在 JDK 1.1中,支持两个新的对象 Reader & Writer, 它们只能用来对文本文件进行操作,而 JDK1.1中的 InputStream & OutputStream 可以对文本文件或二进制文件进行操作。
用FileReader 来读取文件的常用方法是:
FileReader fileReader = new FileReader("test.txt");
BufferedReader bufferReader= new BufferedReader(fr);
用 br.readLine() 来读出数据(comment:这里读取方式的是一行一行地),然后用bufferReader.close() 关闭缓存,用fileReader.close() 关闭文件。
用 FileWriter 来写入文件的常用方法是:
FileWriter fileWriter = new FileWriter("new_test.txt");
PrintWriter out = new PrintWriter(fw);
在用out.print 或 out.println 来往文件中写入数据,out.print 和 out.println的唯一区别是后者写
入数据或会自动开一新行。写完后要记得 用out.close() 关闭输出,用fileWriter.close() 关闭文件。
下面地例子是读取一个文件地内容到另外一个文件中:
import java.io.*;
public class TEST {
private static final String TEMPLATE_PATH = "E:"+File.separator;//假设文件放置在E盘
public static void main(String[] args) {
String lineContent = null;//用来存放读取出来地每一行内容
try{
FileReader fr = new FileReader(TEMPLATE_PATH+"test.txt");
BufferedReader br = new BufferedReader(fr);//读取文件test.txt
FileWriter fw = new FileWriter(TEMPLATE_PATH+"new_test.txt");//创建新文件
PrintWriter out = new PrintWriter(fw);
lineContent = new String();
while ((lineContent = br.readLine()) != null) {//判断是否读取了全部数据,
/*
在这里可以做替换动作
*/
System.out.println(lineContent);
out.print(lineContent);//向新文件输入数据
}
out.close();
fw.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
补充:
文章没有考虑优化,或者最优实现方式,只是给大家提供一种实现方式。
上面的文章(哈哈不管质量如何),是关于文章替换的,本问提供了另外一种实现方式:
import java.io.*;
import java.nio.*;//nio 是J2SDK 1.4 新增的库包,里面引入了chanel概念
import java.nio.channels.*;
import java.nio.charset.*;
public class Search {
private static final String TEMPLATE_PATH = "E:"+File.separator;//假设文件放置在E盘
private String searchWord = null;
public void setSearchWord(String value){
this.searchWord = value;
}
public static void main(String[] args) throws IOException {
//conduct with Chinese-Charset,
Charset charset = Charset.forName("GB18030");
CharsetDecoder decoder = charset.newDecoder();
String fileName = TEMPLATE_PATH +"text.txt";
try{
FileInputStream fis = new FileInputStream(fileName);
FileChannel fc = fis.getChannel();
int sz = (int)fc.size();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
//parse Chinese
CharBuffer cb = decoder.decode(bb);
String s = String.valueOf(cb);
int n = s.indexOf(this.searchWord);
System.out.println(n);//print out the position of the word searchWord
fc.close();
}
catch(Exception e){System.out.println(e);}
}
}