File 程式(Java程式碼)
阿新 • • 發佈:2018-12-30
public static void main(String[] args) {
/*
* 宣告流物件
*/
FileReader fr = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
FileWriter fw = null;
BufferedWriter bw = null;
try {
/*
* 1、讀取模板檔案內容
* 把讀取到的內容臨時存放在stringbuffer物件中
*/
fr = new FileReader("D:/myDoc/pet.template");
br = new BufferedReader(fr);
String str = br.readLine();
while (str != null) {
System.out.println(str);
sb.append(str);
str = br.readLine();
}
/*
* 2、替換讀取的相關內容
*/
String newStr = sb.toString().replace("{name}", "歐歐").replace("{type}", "狗狗").replace("{master}", "李偉");
System.out.println("替換後:" + newStr);
/*
* 3、把生成的新內容,寫入到指定的檔案中
*/
File f = new File("D:/myDoc/pet.txt");
fw = new FileWriter(f);
bw = new BufferedWriter(fw);
bw.write(newStr);
// fw.write(newStr);
System.out.println("write file scuessful!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
/*
* 4.關閉流物件
*/
try {
if (br != null) {
br.close();
}
if(fr != null){
fr.close();
}
if(bw != null){
bw.close();
}
if(fw != null){
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* 宣告流物件
*/
FileReader fr = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
FileWriter fw = null;
BufferedWriter bw = null;
try {
/*
* 1、讀取模板檔案內容
* 把讀取到的內容臨時存放在stringbuffer物件中
*/
fr = new FileReader("D:/myDoc/pet.template");
br = new BufferedReader(fr);
String str = br.readLine();
while (str != null) {
System.out.println(str);
sb.append(str);
str = br.readLine();
}
/*
* 2、替換讀取的相關內容
*/
String newStr = sb.toString().replace("{name}", "歐歐").replace("{type}", "狗狗").replace("{master}", "李偉");
System.out.println("替換後:" + newStr);
/*
* 3、把生成的新內容,寫入到指定的檔案中
*/
File f = new File("D:/myDoc/pet.txt");
fw = new FileWriter(f);
bw = new BufferedWriter(fw);
bw.write(newStr);
// fw.write(newStr);
System.out.println("write file scuessful!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
/*
* 4.關閉流物件
*/
try {
if (br != null) {
br.close();
}
if(fr != null){
fr.close();
}
if(bw != null){
bw.close();
}
if(fw != null){
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}