天天看點

java file類實作List生成本地檔案與續寫本地檔案

public static void main(String []str){
        List<String>  arrList= new ArrayList<String>();
        //創造一千組資料,将其存進arrList中
        for(int m = ;m<;m++){
            String aa1="實驗資料"+m;
            arrList.add(aa1);
        }
        //路徑名稱,為了相容linus最好是使用file類中的分隔符,不要使用“\\”
        String tempDir = "E:\\qqq";
        //你要建立的檔案名稱,一般是檔案名加文本根式,eg:test.txt
        String textName ="tsxt.txt";
        //new一個路徑出來
        File file=new File(tempDir+"\\"+textName);   
        /*判斷該路徑下你需要建立的檔案是否已經存在,若存在,則續寫。若不存在,則建立檔案并寫入*/
        if(!file.exists()) {    
            System.out.println("該目錄"+tempDir+"下沒有檔案可以建立檔案");


             PrintWriter pw = null;
                FileWriter writer = null;
                File newFile=new File(tempDir+"\\"+textName);
            try {    
                writer = new FileWriter(newFile);
                pw = new PrintWriter(writer);
                //文本内輸出語句,實作寫入
                for(int i =; i<arrList.size();i++){
                pw.println(arrList.get(i));
                }
                System.out.println("建立寫入成功");
                } 
            catch (IOException e) {        e.printStackTrace();     }    
            finally{
                try {pw.flush();
                    writer.close();} 
                catch (IOException ex) {ex.printStackTrace();}}
        }  
        else{
        //該路徑下已經存在該檔案,是以可以續寫
            //判斷該檔案是否有寫入權限
            if(file.canWrite()){
             PrintWriter pw = null;
             FileWriter writer = null;
             try 
            {
             writer = new FileWriter(file, true);
             pw = new PrintWriter(writer);
             for(int i =; i<arrList.size();i++){
                    pw.println(arrList.get(i));
                    }
            } 
            catch (IOException e) 
            {
             e.printStackTrace();
            }
            finally{
                try {
                    pw.flush();
                    writer.close();
                } 
                catch (IOException ex) {
                    ex.printStackTrace();
                }
                }
             }
            else{
                System.out.println("該目錄"+tempDir+textName+"沒有寫入權限");
            }
        }
    }