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 南山隐士 阅读(1241) | 评论 (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 南山隐士 阅读(745) | 评论 (0)编辑 收藏

上善若水。水善利万物而不争,处众人之所恶,故几于道。居善地,心善渊,与善仁,言善信,政善治,事善能,动善时。 【解释】 最上等的善要象水一样。水善于滋润万物而不与之争夺,停留在众人讨厌的低洼低方,所以最接近道。居住在善于选择地方,存心善于保持深沉,交友善于真诚相爱,说话善于遵守信用,为政善于有条有理,办事善于发挥能力,行动善于掌握时机。正因为他与事无争,所以才不会招惹怨恨。

posted @ 2008-06-18 15:22 南山隐士 阅读(140) | 评论 (0)编辑 收藏
仅列出标题
共2页: 上一页 1 2