1. 程式人生 > >Java將資料寫入csv檔案使用FTP上傳

Java將資料寫入csv檔案使用FTP上傳

//1.先建立檔案
    public static boolean createFile(String path,String fileName,String fileContent,String companyId) throws IOException{
        Boolean boo=false;
        String tempFileName=path+fileName;
        File file=new File(tempFileName);
        //判斷檔案路徑是否存在,不存在建立資料夾
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        
        //判斷如果檔案不存在,則新建,存在 繼續往裡面寫
        if(!file.exists()){
            file.createNewFile();
            boo=writeFileContent(tempFileName, fileContent,fileName,companyId);
        }else{
            boo=writeFileContent(tempFileName, fileContent,fileName,companyId);
        }
        return boo;
      
    }
    //2. 將內容寫入檔案
    public static boolean writeFileContent(String fileNamePath,String writeContent,String fileName,String companyId) throws IOException{
        boolean boo=false;
        IEmsSchemeMgr iesm=new EmsSchemeMgrImpl();
        //檔案內容換行
        String fileC=writeContent+"\r\n"; //new String(writeContent.getBytes(),"UTF-8") +"\r\n";
        String temp="";
        
        FileInputStream fis=null;
        InputStreamReader isr=null;
        BufferedReader br=null;
        FileOutputStream fos=null;
        PrintWriter pw=null;
        try{
        File file=new File(fileNamePath);
        //將檔案讀入輸入流
        fis=new FileInputStream(file);
        isr=new InputStreamReader(fis);//,""
        br=new BufferedReader(isr);
        
        StringBuffer sb=new StringBuffer();
        //檔案原有內容
        for (int i = 0; (temp=br.readLine())!=null; i++) {
            sb.append(temp);
            //換行
            sb=sb.append(System.getProperty("line.separator"));
        }
        sb.append(fileC);
        fos = new FileOutputStream(file);
        pw = new PrintWriter(fos);
        pw.write(sb.toString().toCharArray());
        pw.flush();
        boo = true;
        long len=(file.length()/1024)+1; //由於整數運算省略小數部分... 故加1
        //將資料儲存在資料庫 3.將寫入檔案的大小,路徑,時間,檔名稱 ,推送狀態  儲存在資料庫  --放在 寫入檔案之後
        EmsReserveEntity reserve=new EmsReserveEntity();
        reserve.setFileName(fileName);
        reserve.setFileSize(String.valueOf(len));
        reserve.setCompanyId(companyId);
        iesm.updateFileSize(reserve);
        
        System.out.println("檔案的大小:"+len);
        }catch(Exception e){
            e.printStackTrace();
        }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 boo;
    }