1. 程式人生 > >專案中遇到的問題與解決方法——持續新增

專案中遇到的問題與解決方法——持續新增

問題解決之前不會,學習解決了之後怕忘記。

純屬為了方便自己回頭看,學習那些曾經不會的。持續新增。

1.要匯入Excel,但是獲取到的數字是科學計數法,比如11001000獲取到的是1.01+E7

 // 把科學計數轉換成常規數字
String s=control.getStrValue("CONTROL_TYPE_NAME");    //s是1.01+E7
BigDecimal bd = new BigDecimal(s);   
String bd1=bd.toPlainString();
備註:最後發現既然是字串型別的,為什麼不把Excel的格式改成文字,改了發現好了,麻麻的

2、驗證URL

if(!ip.matches("\\
b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b")) {mb.setFalseWithMsg("ip地址格式不正確!");};

3、驗證網址

String test="((https|http|ftp|rtsp|mms)?://)?(([0-9a-z_!~*'().&=+$%-
]+: )?[0-9a-z_!~*'().&=+$%-][email protected])?(([0-9]{1,3}\\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\.[a-z]{2,6})(:[0-9]{1,4})?((/?)|(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)"; if(!webServiceAddress.matches(test)) { mb.setFalseWithMsg("webService地址格式不正確"); }

4、將一些資訊生成xml

public String getStr() {
        return "<prop>\n\t<propname>whatName</propname>\n\t<propsign>whatSign</propsign>\n\t<propvalue>null</propvalue>\n</prop>\n";
    }

StringBuffer sb = new StringBuffer();
        sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        // 緩急程度
        String newRapId = getStr().replace("whatName", "緩急程度");
        newRapId = newRapId.replace("whatSign", "rapId");
        if (rapId != null) {
            newRapId = newRapId.replace("null", rapId);
        }
        sb.append(newRapId);
        // 發文單位
        String newCreateUserCompany = getStr().replace("whatName", "發文單位");
        newCreateUserCompany = newCreateUserCompany.replace("whatSign", "createUserCompany");
        if (createUserCompany != null) {
            newCreateUserCompany = newCreateUserCompany.replace("null", createUserCompany);
        }
        sb.append(newCreateUserCompany);
        // 接收單位
        String newReceiveCompanyName = getStr().replace("whatName", "接收單位");
        newReceiveCompanyName = newReceiveCompanyName.replace("whatSign", "receiveCompanyName");
        if (receiveCompanyName != null) {
            newReceiveCompanyName = newReceiveCompanyName.replace("null", receiveCompanyName);
        }
        sb.append(newReceiveCompanyName);
        return sb.toString();


public void writeXml(FileInfo fileInfo) {
        try {
            String xmlFile = parseListToString(fileInfo);
            File filePath = new File("D:/OAFILE");
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            String target = "D:/OAFILE/" + fileInfo.getId() + ".xml";
            FileWriter writer = new FileWriter(target);//這是第一種寫法
            //第二種寫法:這種可以確定編碼型別
Writer writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8"));
            writer.write(xmlFile);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

5、快速複製

public void moveFile(String source, String target) {
        FileChannel in = null;
        FileChannel out = null;
        FileInputStream inStream = null;
        FileOutputStream outStream = null;
        try {
            inStream = new FileInputStream(source);
            outStream = new FileOutputStream(target);
            in = inStream.getChannel();
            out = outStream.getChannel();
            in.transferTo(0, in.size(), out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
                in.close();
                outStream.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

6、從指定地址進行檔案下載

public void downloadFile(String source, String target) {
        try {
            URL url = new URL(source);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target));
            byte[] buffer = new byte[1204];
            int byteRead = 0;
            while ((byteRead = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, byteRead);
            }
            bos.flush();
            bos.close();
            bis.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

7、瀏覽器執行檔案下載

                File file=new File("D:/test.docx");
                final HttpServletResponse response = getResonse();
                response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=temp" + file.getName());
                ServletOutputStream os = response.getOutputStream();
                InputStream is = new FileInputStream(file);
                byte[] buff = new byte[10240];
                int batch;
                while ((batch = is.read(buff)) != -1) {
                    os.write(buff, 0, batch);
                }
                is.close();
                os.close();

8、zip檔案上傳

// 檔案上傳
    public boolean fileUpLoad(String upSource, String upTarget) {
        try {
            URL url = new URL(upTarget);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("content-type", "application/zip");
            BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream());
            // 讀取檔案上傳到伺服器
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(upSource));
            byte[] bytes = new byte[1024];
            int readByte = 0;
            while ((readByte = bis.read(bytes, 0, 1024)) > 0) {
                bos.write(bytes, 0, readByte);
            }
            bos.flush();
            bos.close();
            bis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

9、將資料夾打包成zip

// 壓縮資料夾
    private boolean fileToZip(String sourceFilePath, String zipFilePath, String fileName) {
        File sourceFile = new File(sourceFilePath);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        if (!sourceFile.exists()) {
            System.out.println("要壓縮的資料夾不存在");
            return false;
        } else {
            try {
                File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
                if (zipFile.exists()) {
                    zipFile.delete();// 如果有,先刪除,實現覆蓋
                }
                File[] sourceFiles = sourceFile.listFiles();
                if (null == sourceFiles || sourceFiles.length < 1) {
                    System.out.println("要壓縮的資料夾沒有檔案存在");
                    return false;
                } else {
                    fos = new FileOutputStream(zipFile);
                    zos = new ZipOutputStream(new BufferedOutputStream(fos));
                    byte[] bufs = new byte[1024 * 10];
                    for (int i = 0; i < sourceFiles.length; i++) {
                        // 建立ZIP實體,並新增進壓縮包
                        ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                        zos.putNextEntry(zipEntry);
                        //=====================
                        //使用這句可以確定編碼,但是Java自帶的包沒有這個功能
                        //所以必須用ant.jar
                        //import org.apache.tools.zip.ZipEntry;
                        //import org.apache.tools.zip.ZipOutputStream;
                        zos.setEncoding("gbk");
                        //====================
                        // 讀取待壓縮的檔案並寫進壓縮包裡
                        fis = new FileInputStream(sourceFiles[i]);
                        bis = new BufferedInputStream(fis, 1024 * 10);
                        int read = 0;
                        while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                            zos.write(bufs, 0, read);
                        }
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                // 關閉流
                try {
                    if (null != bis)
                        bis.close();
                    if (null != zos)
                        zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        return true;
    }

10、a標籤的onclick事件不能傳除數字之外的引數。

standardFileName += "&nbsp;<a style='color:black;cursor:pointer;'onclick='downLoad(\""+source+"\");'>" + fileName + "</a>;";

解決方法:引數前後用雙引號,轉義字元後使用。

11、對字串進行MD5加密

        //要加密的字串
        String str="what";
        //確定計算方法
        MessageDigest md=MessageDigest.getInstance("MD5");
        BASE64Encoder encode=new BASE64Encoder();
        //加密後的字串
        String newStr=encode.encode(md.digest(str.getBytes()));
        System.out.println(newStr);

12、匯入zip壓縮包,並且解壓

    try {
        //filePath是要匯入的壓縮包地址;後面必須加Charset.forName("gbk");否則解壓中文檔案報錯
             ZipFile zipFile = new ZipFile(filePath, Charset.forName("gbk"));
            // 獲取ZIP檔案裡所有的entry
            Enumeration entrys = zipFile.entries();
            while (entrys.hasMoreElements()) {
                entry = (ZipEntry) entrys.nextElement();
                entryName = entry.getName();
                String fileSize = String.valueOf(entry.getSize());
                File targetFile = new File(target);
                os = new FileOutputStream(targetFile);
                byte[] buffer = new byte[4096];
                int bytes_read = 0;
                // 從ZipFile物件中開啟entry的輸入流
                is = zipFile.getInputStream(entry);
                while ((bytes_read = is.read(buffer)) != -1) {
                    os.write(buffer, 0, bytes_read);
                }
            }
        } catch (IOException err) {
            System.err.println("解壓縮檔案失敗: " + err);
            flag = false;
        }

13、讀取xml檔案資訊
xml檔案內容:

<prop>
    <propname>標題</propname>
    <propsign>Name</propsign>
    <propvalue>傳送測試</propvalue>
</prop>
<prop>
    <propname>型別</propname>
    <propsign>Type</propsign>
    <propvalue>12</propvalue>
</prop>
<prop>
    <propname>編號</propname>
    <propsign>No</propsign>
    <propvalue>11</propvalue>
</prop>
<prop>
    <propname>成為日期</propname>
    <propsign>sendDate</propsign>
    <propvalue>2017-10-12</propvalue>
</prop>
<prop>
    <propname>密級</propname>
    <propsign>secret</propsign>
    <propvalue>40</propvalue>
</prop>
<prop>
    <propname>密級年</propname>
    <propsign>secretYear</propsign>
    <propvalue>12</propvalue>
</prop>
<prop>
    <propname>緩急程度</propname>
    <propsign>rapId</propsign>
    <propvalue>急件</propvalue>
</prop>

獲取到的都是propvalue的內容

        SAXReader reader = new SAXReader();
        List<String> list = new ArrayList<>();
        try {
            Document doc = reader.read(new File(source));
            Element root = doc.getRootElement();
            for (Iterator i = root.elementIterator("prop"); i.hasNext();) {
                Element foo = (Element) i.next();
                for (Iterator j = foo.elementIterator("propvalue"); j.hasNext();) {
                    Element joo = (Element) j.next();
                    list.add(joo.getText());
                }
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;    
        //===================
        //不使用迴圈一步步讀下去
        //===================
        //內容:
        <?xml version="1.0" encoding="utf-8"?>
        <archman>
        <DocSource>
            <system>OA</system>
            <type>普通檔案</type>
            <toDepts>
                <dept>
                    <deptname>what</deptname>
                    <system>
                        <name>阿斯蒂芬</name>
                        <count>1</count>
                    </system>
                </dept>
                <dept>
                    <deptname>what</deptname>
                    <system>
                        <name>等等</name>
                        <count>1</count>
                    </system>
                </dept>
            </toDepts>
        </DocSource>
        //需要讀取到阿斯蒂芬和等等
            InputStream in=new FileInputStream(new File(source));
            Document doc = reader.read(in);
            Element root = doc.getRootElement();
            Element DocSource=(Element) root.elements().get(0);
            List<Element> toDepts=DocSource.element("toDepts").elements();
            String deptName="";
            for (Element e : toDepts) {
                if(deptName=="") {
                    deptName=e.element("system").element("name").getText();
                }else {
                    deptName+=","+e.element("system").element("name").getText();
                }
            }

14、匯入之前想讓使用者下載模板

<a href="downXmlFileInfo.action" style="color:blue;text-decoration:underline;cursor: pointer;">點選這裡下載xml模板</a>
         String path=Environment.getWebRootPath()+"imp\\template\\";
         String fileName="fileInfo.xml";
         try {
            final HttpServletResponse response = getResonse();
            response.setCharacterEncoding("UTF-8");
            File file = new File(path, fileName);
            String name = file.getName();
            // 需要定義為變數,如果tomcat中定義了Connector port="8080" URIEncoding="UTF-8"則不用轉此code
            String code = "ISO_8859_1";
            name = new String(name.getBytes("UTF-8"), code);
            //關鍵程式碼片
            response.setHeader("Content-disposition", "attachment;filename=" + name);
            ServletOutputStream os = response.getOutputStream();
            //關鍵程式碼片
            InputStream is = new FileInputStream(file);
            byte[] buff = new byte[10240];
            int batch;
            while ((batch = is.read(buff)) != -1) {
                os.write(buff, 0, batch);
            }
            is.close();
            os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

15、js對HTML頁面table增刪行
增加行:

    //.rows.length表示現在已有多少行,可以確保新增行的時候加在最後
    //新增行
    var newTr =  document.getElementById("fileUploadAttach").
    insertRow(document.getElementById("fileUploadAttach").rows.length);  
    //新增行中的列
    var newTd0 = newTr.insertCell();
    newTd0.width="25px;";
    newTd0.align="center";
    var newTd1 = newTr.insertCell();
    newTd1.width="300px;";
    newTd1.align="left";
    var newTd2 = newTr.insertCell();
    newTd2.width="55px;";
    //賦值
    newTd0.innerHTML ="";
    newTd1.innerHTML ="&nbsp;"+fileName;
    newTd2.innerHTML ="<button onclick='deleteFile(this,\""+fileId+"\");return false;'  style='color:black;'>刪除</button>";

刪除所選行:

    function deleteFile(obj,fileId){
    var index=obj.parentNode.parentNode.rowIndex;
    var table = document.getElementById("fileUploadAttach");
    table.deleteRow(index);
    }          

刪除增加的所有行:

    var tab1 = document.getElementById("fileUploadText");
    var rowsText=tab1.rows.length;
    //只能倒著刪
    if(rowsText>1){
        for(var i=rowsText-1;i>0;i--){
            tab1.deleteRow(i);
        }
    }

16、使用ajax的時候加上alert就成功,去掉alert就走不通,資料錯誤
原因:因為alert給了系統賦值的時間,所以有了alert就對了。
解決:ajax加上async:false,就可以了,表示同步。

17、在js中對字串進行替換
問題:只能替換第一個
解決:使用正則替換

    var sendDate=$("[name='fileInfo.sendDate']").val();
    //sendDate:2017-02-05  sendDateNum:20170205
    var sendDateNum=Number(sendDate.replace(/-/g,""));
    強轉為數字,兩個日期可以加減比較大小。

18、使用jQuery獲取input的值獲取不到
原因:字母寫錯了;命名出現重名,獲取的不是你輸入的那個;

19、js操作table,獲取所選行的行號和某一格的值

<button onclick='deleteFile(this)'>刪除</button>
function deleteFile(obj){
    var index=obj.parentNode.parentNode.rowIndex;//獲取行號
    var fileId=$("table").find("tr").eq(2).find("td").eq(4).text();//獲取第2行第4列的值
}

20、使用uploadServlet上傳檔案

        response.setContentType("text/html;charset=UTF-8");
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e1) {
            e1.printStackTrace();
        }
        Iterator itr = items.iterator();
        StringBuffer failMsg = new StringBuffer("");// 失敗原因
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            fn = fileName.substring(fileName.lastIndexOf("/") + 1);
            //副檔名
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            String newFileName = UUID.randomUUID().toString() + "." + fileExt;
            try {
                File uploadedFile = new File(savePath, newFileName);
                item.write(uploadedFile);
            } catch (Exception e) {
                failMsg.append(";系統錯誤,上傳失敗");
                return;
            }
        }
        JSONObject obj = new JSONObject();
        response.getWriter().write(obj.toJSONString());

21、檔案加密與解密

    public static Key getKey() {  
        Key deskey = null;  
        try {  
            // 固定金鑰  
            byte[] buffer = new byte[] { 0x47, 0x33, 0x43, 0x4D, 0x4F, 0x50, 0x31, 0x32 };  
            deskey = (Key) new SecretKeySpec(buffer, "DES");  
        } catch (Exception e) {  
            throw new RuntimeException("Error initializing SqlMap class. Cause: " + e);  
        }  
        return deskey;
    }  
    /**  
      * 檔案file進行加密並儲存目標檔案destFile中  
      *  
      * @param file   要加密的檔案 如c:/test/srcFile.txt  
      * @param destFile 加密後存放的檔名 如c:/加密後文件.txt  
      */   
      public static void encrypt(String file, String destFile) throws Exception {   
        Cipher cipher = Cipher.getInstance( "DES/ECB/PKCS5Padding ");
        cipher.init(Cipher.ENCRYPT_MODE, getKey());   
        InputStream is = new FileInputStream(file);   
        OutputStream out = new FileOutputStream(destFile);   
        CipherInputStream cis = new CipherInputStream(is, cipher);   
        byte[] buffer = new byte[1024];   
        int r;   
        while ((r = cis.read(buffer)) > 0) {   
            out.write(buffer, 0, r);   
        }   
        cis.close();   
        is.close();   
        out.close();   
      }
      /**  
       * 檔案採用DES演算法解密檔案  
       *  
       * @param file 已加密的檔案 如c:/加密後文件.txt  
       * @param destFile  
       * 解密後存放的檔名 如c:/ test/解密後文件.txt  
       */   
       public static void decrypt(String source){   
        InputStream is=null;
        OutputStream out=null;
        CipherOutputStream cos=null;
        File file=new File(source);
        File destFile=new File("D://12"+source.substring(source.lastIndexOf(".")));
        try {
            Cipher cipher = Cipher.getInstance("DES");   
             cipher.init(Cipher.DECRYPT_MODE, getKey()); 
             is = new FileInputStream(file);   
             out = new FileOutputStream(destFile);   
             cos = new CipherOutputStream(out, cipher);   
             byte[] buffer = new byte[1024];   
             int r;   
             while ((r = is.read(buffer)) >= 0) {   
                 System.out.println();  
                 cos.write(buffer, 0, r);   
             }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
             try {
                cos.close();   
                 out.close();   
                 is.close();
                 file.delete();
                 destFile.renameTo(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("解密完成");
       }

22、在for迴圈中操作檔案無效
解決:for迴圈採用倒序就可以了。

23、檔案解壓後文件持續佔用
問題一:壓縮包刪除不了
解決:除了關閉流,還要關閉zipFile。zipFile.close();
問題二:解壓好的檔案操作時表示佔用
解決:關閉流之後加上System.gc();

24、jedis使用
jedis.properties:

host=193.122.1.21
port=6379
maxTotal=20
maxIdle=10

JedisUtils.java:

public class JedisUtils {

    private static int maxTotal = 0;
    private static int maxIdle = 0;
    private static String host = null;
    private static int port = 0;

    private static JedisPoolConfig config = new JedisPoolConfig();
    static {
        // 讀取配置檔案
        InputStream in = JedisUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
        Properties pro = new Properties();
        try {
            pro.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        maxTotal = Integer.parseInt(pro.getProperty("maxTotal"));
        maxIdle = Integer.parseInt(pro.getProperty("maxIdle"));
        port = Integer.parseInt(pro.getProperty("port"));
        host = pro.getProperty("host");
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
    }

    private static JedisPool pool = new JedisPool(config, host, port);

    // 提供一個返回池子的方法
    public static JedisPool getPool() {
        return pool;
    }

    // 獲得一個jedis資源方法
    public static Jedis getJedis() {
        return pool.getResource();
    }

    // 關閉的方法
    public static void close(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

}

25、Java實現控制開啟網頁連結及關閉

        String site="http://mp.weixin.qq.com/s/5WDhPf1meNCZ4YVyXbJt2Q";
        try {  
            Desktop desktop = Desktop.getDesktop();  
            URI url = new URI(site);  
            for (int i = 0; i < 10; i++) {
                //執行這裡就可以打開了
                desktop.browse(url);
            }
            Thread.sleep(8000);
            //用360chrome.exe開啟,所以這裡關閉這個。
            Runtime.getRuntime().exec("taskkill /F /IM 360chrome.exe"); 
        } catch (Exception e) {
            e.printStackTrace();
        }

26、oracle日期操作

//date轉換成timestamp
SELECT CAST(SYSDATE AS TIMESTAMP) FROM DUAL;
//timestamp型別轉換為date型別
SELECT CAST(CREATE_TIME AS DATE) FROM XTABLE;
//計算date型別之間相差天數
SELECT ROUND(DATE1-DATE2) FROM XTABLE;
//計算timestamp型別之間相差的天數
SELECT ROUND(CAST(TIMESTAMP1 AS DATE)-CAST(TIMESTAMP2 AS DATE)) FROM XTABLE;

27、存資料庫前,轉換date或String到timestamp型別

        //date
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Timestamp.valueOf(sdf.format(new Date()));
        //字串
        String str="2017-10-11";
        Timestamp.valueOf(str+" 00:00:00");

28、專案新增定時器

//1、新建一個class類,實現servletContextListener介面,類中寫定時器和呼叫的方法
//2、在web.XML中配置監聽器就可以了
public class clearFileTimer implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub

    }
    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        Runnable runnable = new Runnable() {
            public void run() {
                clearFile clear = new clearFile();
                try {
                    while (true) {
                        // 10天執行一次刪除操作
                        long sleep = 10 * 86400 * 1000;
                        Thread.sleep(sleep);
                        clear.clearIt();// 呼叫的方法
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

        //=============
        //web.xml檔案
        //=========
        <listener>
            <listener-class>
                com.test.what.impl.clearFileTimer
            </listener-class>
        </listener>

29、定時器第二種寫法

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Timer;
import java.util.TimerTask;

public class updateStateTimer implements ServletContextListener{

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        updateState t = new updateState();//預設執行updateState這個類中的run方法
        Timer timer=new Timer(true);
        long period=24*60*60*1000;
        timer.schedule(t, 20000, period); //t表示執行的類(中的run方法),20000表示延遲,period表示間隔
    }
}

class updateState extends TimerTask {
    @Override
    public void run() {
        new SendListMan().updateStateEveryday();
    }
}

30、斷點續傳與非斷電續傳兩端寫法

//接收檔案端:
public void wsReceive(String fileByte,String fileName) {    //fileByte表示檔案轉換成的字串
        //檔名稱和路徑
        String zipSource = "D:/"+fileName;
        FileOutputStream fos = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes = decoder.decodeBuffer(fileByte);
            fos = new FileOutputStream(zipSource,true);//後面加true,表示檔案存在時,內容疊加(斷點續傳)
            fos = new FileOutputStream(zipSource);//表示產生新的檔案,會覆蓋之前的所有內容(非斷點續傳)
            fos.write