1. 程式人生 > >java建立txt檔案並存入內容

java建立txt檔案並存入內容

[java] view plain copy
import java.io.BufferedReader;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.PrintWriter;  
  
public class txtExport {  
  
    private static String path = "D:/";  
    private static String filenameTemp;  
  
    public static void main(String[] args) throws IOException {  
        txtExport.creatTxtFile("你好");  
        txtExport.writeTxtFile("你好");  
    }  
      
      
    /** 
     * 建立檔案 
     *  
     * @throws IOException 
     */  
    public static boolean creatTxtFile(String name) throws IOException {  
        boolean flag = false;  
        filenameTemp = path + name + ".txt";  
        File filename = new File(filenameTemp);  
        if (!filename.exists()) {  
            filename.createNewFile();  
            flag = true;  
        }  
        return flag;  
    }  
  
    /** 
     * 寫檔案 
     *  
     * @param newStr 
     *            新內容 
     * @throws IOException 
     */  
    public static boolean writeTxtFile(String newStr) throws IOException {  
        // 先讀取原有檔案內容,然後進行寫入操作  
        boolean flag = false;  
        String filein = newStr + "\r\n";  
        String temp = "";  
  
        FileInputStream fis = null;  
        InputStreamReader isr = null;  
        BufferedReader br = null;  
  
        FileOutputStream fos = null;  
        PrintWriter pw = null;  
        try {  
            // 檔案路徑  
            File file = new File(filenameTemp);  
            // 將檔案讀入輸入流  
            fis = new FileInputStream(file);  
            isr = new InputStreamReader(fis);  
            br = new BufferedReader(isr);  
            StringBuffer buf = new StringBuffer();  
  
            // 儲存該檔案原有的內容  
            for (int j = 1; (temp = br.readLine()) != null; j++) {  
                buf = buf.append(temp);  
                // System.getProperty("line.separator")  
                // 行與行之間的分隔符 相當於“\n”  
                buf = buf.append(System.getProperty("line.separator"));  
            }  
            buf.append(filein);  
  
            fos = new FileOutputStream(file);  
            pw = new PrintWriter(fos);  
            pw.write(buf.toString().toCharArray());  
            pw.flush();  
            flag = true;  
        } catch (IOException e1) {  
            // TODO 自動生成 catch 塊  
            throw e1;  
        } finally {  
            if (pw != null) {  
                pw.close();  
            }  
            if (fos != null) {  
                fos.close();  
            }  
            if (br != null) {  
                br.close();  
            }  
            if (isr != null) {  
                isr.close();  
            }  
            if (fis != null) {  
                fis.close();  
            }  
        }  
        return flag;  
    }  
  
}