posts - 13,comments - 19,trackbacks - 0
          這需要導入java.io類
          import java.io.*;

          public class FileOperate {
            public FileOperate() {
            }

            /**
             * 新建目錄
             * @param folderPath String 如 c:/fqf
             * @return boolean
             */
            public void newFolder(String folderPath) {
              try {
                String filePath = folderPath;
                filePath = filePath.toString();
                java.io.File myFilePath = new java.io.File(filePath);
                if (!myFilePath.exists()) {
                  myFilePath.mkdir();
                }
              }
              catch (Exception e) {
                System.out.println("新建目錄操作出錯");
                e.printStackTrace();
              }
            }

            /**
             * 新建文件
             * @param filePathAndName String 文件路徑及名稱 如c:/fqf.txt
             * @param fileContent String 文件內容
             * @return boolean
             */
            public void newFile(String filePathAndName, String fileContent) {

              try {
                String filePath = filePathAndName;
                filePath = filePath.toString();
                File myFilePath = new File(filePath);
                if (!myFilePath.exists()) {
                  myFilePath.createNewFile();
                }
                FileWriter resultFile = new FileWriter(myFilePath);
                PrintWriter myFile = new PrintWriter(resultFile);
                String strContent = fileContent;
                myFile.println(strContent);
                resultFile.close();

              }
              catch (Exception e) {
                System.out.println("新建目錄操作出錯");
                e.printStackTrace();

              }

            }

            /**
             * 刪除文件
             * @param filePathAndName String 文件路徑及名稱 如c:/fqf.txt
             * @param fileContent String
             * @return boolean
             */
            public void delFile(String filePathAndName) {
              try {
                String filePath = filePathAndName;
                filePath = filePath.toString();
                java.io.File myDelFile = new java.io.File(filePath);
                myDelFile.delete();

              }
              catch (Exception e) {
                System.out.println("刪除文件操作出錯");
                e.printStackTrace();

              }

            }

            /**
             * 刪除文件夾
             * @param filePathAndName String 文件夾路徑及名稱 如c:/fqf
             * @param fileContent String
             * @return boolean
             */
            public void delFolder(String folderPath) {
              try {
                delAllFile(folderPath); //刪除完里面所有內容
                String filePath = folderPath;
                filePath = filePath.toString();
                java.io.File myFilePath = new java.io.File(filePath);
                myFilePath.delete(); //刪除空文件夾

              }
              catch (Exception e) {
                System.out.println("刪除文件夾操作出錯");
                e.printStackTrace();

              }

            }

            /**
             * 刪除文件夾里面的所有文件
             * @param path String 文件夾路徑 如 c:/fqf
             */
            public void delAllFile(String path) {
              File file = new File(path);
              if (!file.exists()) {
                return;
              }
              if (!file.isDirectory()) {
                return;
              }
              String[] tempList = file.list();
              File temp = null;
              for (int i = 0; i < tempList.length; i++) {
                if (path.endsWith(File.separator)) {
                  temp = new File(path + tempList[i]);
                }
                else {
                  temp = new File(path + File.separator + tempList[i]);
                }
                if (temp.isFile()) {
                  temp.delete();
                }
                if (temp.isDirectory()) {
                  delAllFile(path+"/"+ tempList[i]);//先刪除文件夾里面的文件
                  delFolder(path+"/"+ tempList[i]);//再刪除空文件夾
                }
              }
            }

            /**
             * 復制單個文件
             * @param oldPath String 原文件路徑 如:c:/fqf.txt
             * @param newPath String 復制后路徑 如:f:/fqf.txt
             * @return boolean
             */
            public void copyFile(String oldPath, String newPath) {
              try {
                int bytesum = 0;
                int byteread = 0;
                File oldfile = new File(oldPath);
                if (oldfile.exists()) { //文件存在時
                  InputStream inStream = new FileInputStream(oldPath); //讀入原文件
                  FileOutputStream fs = new FileOutputStream(newPath);
                  byte[] buffer = new byte[1444];
                  int length;
                  while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字節數 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                  }
                  inStream.close();
                }
              }
              catch (Exception e) {
                System.out.println("復制單個文件操作出錯");
                e.printStackTrace();

              }

            }

            /**
             * 復制整個文件夾內容
             * @param oldPath String 原文件路徑 如:c:/fqf
             * @param newPath String 復制后路徑 如:f:/fqf/ff
             * @return boolean
             */
            public void copyFolder(String oldPath, String newPath) {

              try {
                (new File(newPath)).mkdirs(); //如果文件夾不存在 則建立新文件夾
                File a=new File(oldPath);
                String[] file=a.list();
                File temp=null;
                for (int i = 0; i < file.length; i++) {
                  if(oldPath.endsWith(File.separator)){
                    temp=new File(oldPath+file[i]);
                  }
                  else{
                    temp=new File(oldPath+File.separator+file[i]);
                  }

                  if(temp.isFile()){
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                        (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ( (len = input.read(b)) != -1) {
                      output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                  }
                  if(temp.isDirectory()){//如果是子文件夾
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                  }
                }
              }
              catch (Exception e) {
                System.out.println("復制整個文件夾內容操作出錯");
                e.printStackTrace();

              }

            }

            /**
             * 移動文件到指定目錄
             * @param oldPath String 如:c:/fqf.txt
             * @param newPath String 如:d:/fqf.txt
             */
            public void moveFile(String oldPath, String newPath) {
              copyFile(oldPath, newPath);
              delFile(oldPath);

            }

            /**
             * 移動文件到指定目錄
             * @param oldPath String 如:c:/fqf.txt
             * @param newPath String 如:d:/fqf.txt
             */
            public void moveFolder(String oldPath, String newPath) {
              copyFolder(oldPath, newPath);
              delFolder(oldPath);

            }
          }



          java中刪除目錄事先要刪除目錄下的文件或子目錄。用遞歸就可以實現。這是我第一個用到算法作的程序,哎看來沒白學。
          public void del(String filepath) throws IOException{
          File f = new File(filepath);//定義文件路徑       
          if(f.exists() && f.isDirectory()){//判斷是文件還是目錄
              if(f.listFiles().length==0){//若目錄下沒有文件則直接刪除
                  f.delete();
              }else{//若有則把文件放進數組,并判斷是否有下級目錄
                  File delFile[]=f.listFiles();
                  int i =f.listFiles().length;
                  for(int j=0;j<i;j++){
                      if (delFile[j].isDirectory()){                                                del (delFile[j].getAbsolutePath());//遞歸調用del方法并取得子目錄路徑
                      }
                      delFile[j].delete();//刪除文件
                  }
              }
              del(filepath);//遞歸調用
          }

          }    


          刪除一個非空目錄并不是簡單地創建一個文件對象,然后再調用delete()就可以完成的。要在平臺無關的方式下安全地刪除一個非空目錄,你還需要一個算法。該算法首先刪除文件,然后再從目錄樹的底部由下至上地刪除其中所有的目錄。

          只要簡單地在目錄中循環查找文件,再調用delete就可以清除目錄中的所有文件:

          static public void emptyDirectory(File directory) {
             File[ ] entries = directory.listFiles( );
             for(int i=0; i<entries.length; i++) {
                 entries[i].delete( );
             }
          }
          這個簡單的方法也可以用來刪除整個目錄結構。當在循環中遇到一個目錄時它就遞歸調用deleteDirectory,而且它也會檢查傳入的參數是否是一個真正的目錄。最后,它將刪除作為參數傳入的整個目錄。
          static public void deleteDirectory(File dir) throws IOException {
             if( (dir == null) || !dir.isDirectory) {
                 throw new IllegalArgumentException(

                           "Argument "+dir+" is not a directory. "
                       );
             }

             File[ ] entries = dir.listFiles( );
             int sz = entries.length;

             for(int i=0; i<sz; i++) {
                 if(entries[i].isDirectory( )) {
                     deleteDirectory(entries[i]);
                 } else {
                     entries[i].delete( );
                 }
             }

            dir.delete();
          }
          在Java 1.1以及一些J2ME/PersonalJava的變種中沒有File.listFiles方法。所以只能用File.list,它的返回值一個字符串數組,你要為每個字符串構造一個新的文件對象。
          posted @ 2008-06-25 08:25 南山隱士 閱讀(1246) | 評論 (0)編輯 收藏

          WebLogic Server包含了Timer Service功能,你可以指定某一時刻或某一時間間隔產生Timer事件,同時你可以使用委托代理的機制,為這個事件注冊事件監聽器,以實現Timer Service功能。

            WebLogic Server 7.0以后的版本,WebLogic Timer Service擴展自標準的JMX Timer Service,使其可以運行于WebLogic Server的執行線程中,并且享有WebLogic Server的安全上下文環境,也就是說,可以在代碼中得到安全信息,如用戶名等。下面結合一個實例演示其功能。

          File:TimerServiceListener.java

          package org.yekki.weblogic.timer;

          import java.util.Date;

          import java.util.Random;

          import javax.jms.JMSException;

          import javax.jms.Queue;

          import javax.jms.QueueConnection;

          import javax.jms.QueueConnectionFactory;

          import javax.jms.QueueSender;

          import javax.jms.QueueSession;

          import javax.jms.Session;

          import javax.jms.TextMessage;

          import javax.management.InstanceNotFoundException;

          import javax.management.Notification;

          import javax.management.NotificationListener;

          import javax.naming.Context;

          import javax.naming.InitialContext;

          import javax.servlet.ServletContext;

          import javax.servlet.ServletContextEvent;

          import javax.servlet.ServletContextListener;

          import org.apache.ecs.xml.XML;

          import weblogic.management.timer.Timer;

          public class TimerServiceListener

                 implements ServletContextListener, NotificationListener {

                 private long period;

                 private boolean debug;

                 private Timer timer;

                 private Integer notificationId;

                 private QueueConnectionFactory factory;

                 private QueueConnection connection;

                 private QueueSession session;

                 private QueueSender sender;

                 private Queue queue;

                 private Context ctx;

                 public void contextInitialized(ServletContextEvent event) {

                        initParams(event);

                        initJMS();

                        debug(">>> contextInitialized called.");

                        timer = new Timer();

                        timer.addNotificationListener(this, null, "Message Broker ");

                        Date timerTriggerAt = new Date((new Date()).getTime() + 5000L);

                        notificationId =

                               timer.addNotification(

                                      "Timer Type",

                                      "Timer Message",

                                      this,

                                      timerTriggerAt,

                                      period);

                        timer.start();

                        debug(">>> timer started.");

                        printBrief();

                 }

                 public void initParams(ServletContextEvent event) {

                        ServletContext ctx = event.getServletContext();

                        try {

                               debug = Boolean.valueOf((String)ctx.getInitParameter("debug")).booleanValue();

                        }

                        catch (Exception e) {

                               debug = false;

                               e.printStackTrace();

                        }

                        try {

                               /*

                                second:1000L

                                minute:60000L

                                hour:3600000L

                                day:86400000L

                                week:604800000L

                                */

                               period =

                                      Long

                                             .valueOf((String)ctx.getInitParameter("period"))

                                             .longValue();

                        }

                        catch (Exception e) {

                               period = Timer.ONE_MINUTE;

                               e.printStackTrace();

                        }

                        debug(">>> initialized application parameters.");

                 }

                 private void initJMS() {

                        try {

                               ctx = new InitialContext();

                               factory =

                                      (QueueConnectionFactory)ctx.lookup(

                                             "javax.jms.QueueConnectionFactory");

                               queue = (Queue)ctx.lookup("queue");

                               connection = factory.createQueueConnection();

                               session =

                                      connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

                               sender = session.createSender(queue);

                               connection.start();

                               debug(">>> initialized jms.");

                        }

                        catch (Exception e) {

                               e.printStackTrace();

                        }

                 }

                 public void sendMessage(String message) {

                        try {

                               TextMessage msg = session.createTextMessage();

                               msg.setText(message);

                               sender.send(msg);

                               debug(">>> ################################");

                               debug("Send a message on " + new Date());

                               debug(message);

                               debug(">>> ################################");

                        }

                        catch (JMSException e) {

                               e.printStackTrace();

                        }

                 }

                 public void contextDestroyed(ServletContextEvent event) {

                        debug(">>> contextDestroyed called.");

                        try {

                               timer.stop();

                               timer.removeNotification(notificationId);

                               debug(">>> timer stopped.");

                        }

                        catch (InstanceNotFoundException e) {

                               e.printStackTrace();

                        }

                        try {

                               if (session != null)

                                      session.close();

                               if (connection != null)

                                      connection.close();

                               debug(">>> closed jms connection and session.");

                        }

                        catch (JMSException e) {

                               e.printStackTrace();

                        }

                 }

                 private void printBrief() {

                        String d = "";

                        d = debug ? "ON" : "OFF";

                        print(">>> ################################");

                        print(">>> Author: Niu Xiuyuan");

                        print(">>> EMail: niuxiuyuan@bea.com.cn");

                        print(">>> Company: BEA Systems");

                        print("");

                        print(">>> Debug: " + d);

                        print(">>> Period: " + getPeriodInfo(period));

                        print(">>> ################################");

                 }

                 private void print(String str) {

                        System.out.println(str);

                 }

                 private String getPeriodInfo(long p) {

                        if (p == Timer.ONE_DAY)

                               return "One Day";

                        if (p == Timer.ONE_HOUR)

                               return "One Hour";

                        if (p == Timer.ONE_MINUTE)

                               return "One Minute";

                        if (p == Timer.ONE_SECOND)

                               return "One Second";

                        if (p == Timer.ONE_WEEK)

                               return "One Week";

                        return "Unsupported time period!! period=" + p;

                 }

                 public void handleNotification(Notification notif, Object handback) {

                        Random rnd = new Random();

                        sendMessage(genXML(rnd.nextInt(10)));

                 }

                 public String genXML(int id) {

                        String username = "guru";

                        String password = "niu986";

                        XML usernameXML = null;

                        XML idXML = null;

                        XML passwordXML = null;

                        XML userXML = null;

                        XML profileXML = new XML("profiles");

                        for (int i = 1; i <= id; i++) {

                               usernameXML = (new XML("user")).addElement(username);

                               idXML = (new XML("id")).addElement(Integer.toString(id));

                               passwordXML = (new XML("password")).addElement(password);

                               userXML =

                                      (new XML("user"))

                                             .addXMLAttribute("age", "27")

                                             .addElement(idXML)

                                             .addElement(usernameXML)

                                             .addElement(passwordXML);

                               profileXML.addElement(userXML);

                        }

                        return profileXML.toString();

                 }

                 private void debug(String msg) {

                        if (debug) {

                               System.out.println(msg);

                        }

                 }

                 public static void main(String[] args) {

                 }

          }

            說明:為了方便演示,此類中包含了事件產生器代碼與事件監聽器代碼。使用ServletContextListener接口來控制Timer的啟動與停止。

          File:web.xml

          <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

          <web-app>

            <context-param>

              <param-name>debug</param-name>

              <param-value>false</param-value>

            </context-param>

            <context-param>

              <param-name>period</param-name>

              <param-value>60000</param-value>

            </context-param>

            <listener>

              <listener-class>org.yekki.weblogic.timer.TimerServiceListener</listener-class>

            </listener>

            <login-config>

              <auth-method></auth-method>

            </login-config>

          </web-app>

            說明:我們將webappLisener注冊,并且指定事件產生的時間間隔

              將此WebApp部署到WebLogic Server上,然后通過中端(例如:DOS窗口)查看實驗結果。

            附:本例中使用了ApacheECS項目類庫,您可以訪問如下URL:

            http://jakarta.apache.org/ecs/index.html

          posted @ 2008-06-23 10:16 南山隱士 閱讀(748) | 評論 (0)編輯 收藏

          上善若水。水善利萬物而不爭,處眾人之所惡,故幾于道。居善地,心善淵,與善仁,言善信,政善治,事善能,動善時。 【解釋】 最上等的善要象水一樣。水善于滋潤萬物而不與之爭奪,停留在眾人討厭的低洼低方,所以最接近道。居住在善于選擇地方,存心善于保持深沉,交友善于真誠相愛,說話善于遵守信用,為政善于有條有理,辦事善于發揮能力,行動善于掌握時機。正因為他與事無爭,所以才不會招惹怨恨。

          posted @ 2008-06-18 15:22 南山隱士 閱讀(141) | 評論 (0)編輯 收藏
          僅列出標題
          共2頁: 上一頁 1 2 
          主站蜘蛛池模板: 凤城市| 宜黄县| 饶河县| 健康| 新宁县| 永修县| 大足县| 东莞市| 原平市| 老河口市| 常熟市| 桃江县| 永仁县| 壶关县| 福建省| 阳信县| 三亚市| 邹平县| 安图县| 乐清市| 敦化市| 涿州市| 镇巴县| 城口县| 增城市| 临朐县| 东丰县| 宁陕县| 商水县| 方山县| 色达县| 桦甸市| 改则县| 建昌县| 城固县| 阿坝| 万载县| 泾川县| 乐清市| 廉江市| 德阳市|