1. 程式人生 > 實用技巧 >java 讀取本地檔案 更改

java 讀取本地檔案 更改

部分參考

https://blog.csdn.net/Bancroft_boy/article/details/81126478

package IO;
 
import java.io.*;
 
public class test {
 
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("D://1.txt");
        InputStreamReader isr=new InputStreamReader(fis,"GB2312");
        BufferedReader br 
= new BufferedReader(isr); FileOutputStream fos =new FileOutputStream("E://2.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos,"GB2312"); BufferedWriter bw =new BufferedWriter(osw); int i=0; while((i=br.read())!=-1){ bw.write(i); } bw.close(); br.close(); } }

來說我自己做的

首先是檔案處理方法

我選擇的是字元流 不然的話會出現亂碼情況

 
           /**
            * @Title: MakeHtml 
            * @Description: 建立html
            * @param    filePath 設定模板檔案
            * @param    conent 替換的內容
            * @param    disrPath  生成html的存放路徑
            * @param    fileName  生成html名字 
            * 
@return void 返回型別 * @throws */ public static void MakeHtml(String filePath,String conent,String disrPath,String fileName ){ InputStreamReader bis = null; try { System.out.print(filePath); String templateContent = ""; FileInputStream fileinputstream = new FileInputStream(filePath);// 讀取模板檔案 StringBuffer sb = new StringBuffer(); bis = new InputStreamReader(fileinputstream,"UTF-8"); BufferedReader br = new BufferedReader(bis); int i=0; while((i=br.read())!=-1){ sb.append((char)i); } templateContent = sb.toString(); templateContent = templateContent.replaceAll("模板內容", conent); String fileame = fileName + ".html"; fileame = disrPath+"/" + fileame;// 生成的html檔案儲存路徑。 FileOutputStream fileoutputstream = new FileOutputStream(fileame);// 建立檔案輸出流 System.out.print("檔案輸出路徑:"); System.out.print(fileame); /*byte tag_bytes[] = templateContent.getBytes(); fileoutputstream.write(tag_bytes); fileoutputstream.close();*/ OutputStreamWriter osw = new OutputStreamWriter(fileoutputstream,"UTF-8"); BufferedWriter bw =new BufferedWriter(osw); /*int j=0; while((j=br.read())!=-1){ bw.write(j); }*/ bw.write(templateContent); bw.close(); } catch (Exception e) { System.out.print(e.toString()); e.printStackTrace(); }finally{ try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } }

然後呼叫

        FileUtil.MakeHtml("E:\\testExport\\template.html", "111111", "E:\\testExport\\export", "aaa");