随笔 - 20  文章 - 2  trackbacks - 0
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

常用链接

留言簿(1)

随笔档案

相册

搜索

  •  

最新评论

阅读排行榜

评论排行榜

 

引用

蒋委员长如何将class打包exe文件
class文件打包exe文件要经过两个步骤:
第一步:将class文件打包成jar文件,请参见我的上一篇文章:http://maidini.blog.163.com/blog/static/37762704200848910573/
第二步:将jar文件打包成exe文件。这是今天的重点

将jar打包exe 有许多工具,我以exe4j为例详解打包过程:
第一步:下载exe4j,最新版本为4.1 如下图 exe4j的官方网站 
引用 如何将class打包exe文件 - 紫依韵 - 见人还是人

第二步:运行exe4j.exe 我使用的是免安装版(zip) 如下图
引用 如何将class打包exe文件 - 紫依韵 - 见人还是人

第三步:运行软件exe4j,然后点击Next
引用 如何将class打包exe文件 - 紫依韵 - 见人还是人

第四步:选择第二项"JAR in EXE mode",然后点击Next
引用 如何将class打包exe文件 - 紫依韵 - 见人还是人

第五步:在General中填入名称,在Directories填入生成exe的目录位置。如下图:我将生成exe目录设置为C:\ok ,然后点Next
引用 如何将class打包exe文件 - 紫依韵 - 见人还是人

第六步:Executable name处填入生成exe文件的名称,Icon File处填写图标文件位置,再点Next
引用 如何将class打包exe文件 - 紫依韵 - 见人还是人

第七步:首先设置Class Path的位置,即jar文件的位置。然后点OK
引用 如何将class打包exe文件 - 紫依韵 - 见人还是人

第八步:接着设置Main-Class 的位置,即main方法所在的位置。然后点OK 如下图
引用 如何将class打包exe文件 - 紫依韵 - 见人还是人

设置完成后,如下图: 一定要先设置Class Path,再设置Main class
引用 如何将class打包exe文件 - 紫依韵 - 见人还是人

第九步:填写版本号,最好不要填写第二项。否则可能造成错误(见后面),最后点击Finish即可
引用 如何将class打包exe文件 - 紫依韵 - 见人还是人

错误内容:No JVM could be found on your system. Please define EXE4J_JAVA_HOME to point to an installed JDK or JRE or download a JRE from www.java.com
当时出现这个错误,查看了JDK和JRE都没有问题,exe4j也是最新版。后来才发现是设置"Maximum version"。如果不填写"Maximum version",就不报错。也不知道是不是exe4j的BUG
引用 如何将class打包exe文件 - 紫依韵 - 见人还是人

第十步:完成所有设置,点击“Click Here to Start the Application”可以运行测试生成的EXE文件
引用 如何将class打包exe文件 - 紫依韵 - 见人还是人

生成的最终的EXE程序,双击直接运行。现在可以把自己写的小程序发给朋友们玩玩啦,呵呵
引用 如何将class打包exe文件 - 紫依韵 - 见人还是人



文章来源:http://wxq594808632.blog.163.com/blog/static/10907975520093842753860
posted @ 2009-04-08 16:28 武志强 阅读(1953) | 评论 (0)编辑 收藏

 

引用

蒋委员长如何将Class打包Jar文件--Eclipse
开发环境:Eclipse + Win XP SP2
使用插件:Fatjar、Jigloo

闲话少说,直接切入正题。首先打开Eclipse,创建一个Java工程。如下图:我机子上的是JDK1.6
引用 如何将Class打包Jar文件--Eclipse - 紫依韵 - 见人还是人

第二步:用Jigloo插件创建一个窗体,为了更明显演示我将窗体名字修改为“这是一个测试程序”。如下图:
引用 如何将Class打包Jar文件--Eclipse - 紫依韵 - 见人还是人

第三步:现在就该将运行正常的java程序打包成jar文件。我使用Fatjar插件打包相当方便、傻瓜。直接右键选择要打包的工程,弹出的菜单中选择“Build Fat Jar”。如下图:
引用 如何将Class打包Jar文件--Eclipse - 紫依韵 - 见人还是人

第四步:弹出对话框,需要将引导路径修改,其他选项使用默认设置,然后点击Finish。“Main-Class”这项修改为Main方法所在的文件。此步不可缺少,否则打包的Jar文件双击不可运行。
引用 如何将Class打包Jar文件--Eclipse - 紫依韵 - 见人还是人

稍等一下,就打包成功如下图:出现一个testexe_fat.jar文件。
引用 如何将Class打包Jar文件--Eclipse - 紫依韵 - 见人还是人

进入工程所在的目录也可以看到一个testexe_fat.jar文件,双击它,就运行了。如果无误应该弹出像图2的界面。如下图:
引用 如何将Class打包Jar文件--Eclipse - 紫依韵 - 见人还是人

选择jar文件右键,点击open。相当于双击jar文件如下图:
引用 如何将Class打包Jar文件--Eclipse - 紫依韵 - 见人还是人

总结:打包Jar文件是将分散Class文件统一封装的好办法。双击运行速度与没打包前运行速度没有区别。打包一定要设置好Main-Class的路径,否则JVM找不到入口程序。

如果不知道如何在Eclipse中安装插件,请参见我的另一篇文章:http://maidini.blog.163.com/blog/static/37762704200832671334860/



文章来源:http://wxq594808632.blog.163.com/blog/static/1090797552009384273607
posted @ 2009-04-08 16:27 武志强 阅读(3157) | 评论 (2)编辑 收藏

 

引用

蒋委员长Eclipse的插件安装

众所周知,Eclipse无法方便快速的开发Swing程序。因为Eclipse没有自带图形化编码窗口,如果要开发图形化程序,只有手动敲代码非常不方便。现在有一个插件Jigloo提供图形化程序开发窗口,可以即拖即显。如何将它安装到Eclipse当中呢?

安装插件一般使用Link方式:Link意味链接,Eclipse加载时通过链接找到安装的插件
引用 Eclipse的插件安装 - 紫依韵 - 见人还是人
如上图所示:我的Eclipse路径C:\Program Files\Eclipse 然后将Jigloo解压到Eclipse安装目录中。这里需要注意Jigloo目录下必须要有个叫Eclipse的目录,Eclipse的目录下才是放入features和plugins目录。以上图为例:C:\Program Files\Eclipse\Jigloo\Eclipse 路径里放入features和plugins目录,即features目录路径为:C:\Program Files\Eclipse\Jigloo\Eclipse\features,plugins目录路径为:C:\Program Files\Eclipse\Jigloo\Eclipse\plugins  这里必须要强调目录路径,因为我使用的是Link方式安装插件。

插件安装位置正确后,就该链接了(Link)。在Eclipse路径C:\Program Files\Eclipse下建立一个links目录(必须这个名字),并在links目录下建立一个Jigloo.link的文件(文件名必须同插件目录名相同,后缀名必须是link)。最后用记事本打开Jigloo.link文件,填入path = Jigloo(path = 插件目录名)。保存后,重新启动Eclipse。如下图
引用 Eclipse的插件安装 - 紫依韵 - 见人还是人
在新建项目中出现了一个叫GUI Forms的项目,说明插件安装成功,这就是Jigloo插件提供的图形化开发工具。

写在最后:
向大家推荐一个插件Aptana,这个插件可以调试Javascript代码和HTML代码。此插件还是第一款支持ajax调试的程序。详见http://www.aptana.com/  插件下载地址http://update.aptana.com/install/studio/3.2/
引用 Eclipse的插件安装 - 紫依韵 - 见人还是人
因为新版本要收费(只有一个月免费试用),我使用的老版本,安装到Eclipse中有3个按钮(如上图,黄色惊叹号和红色叉)


文章来源:http://wxq594808632.blog.163.com/blog/static/1090797552009384255251
posted @ 2009-04-08 16:26 武志强 阅读(2280) | 评论 (0)编辑 收藏

如题,废话不多说。

JSP页面

hello.jsp

<%@ page contentType="text/html; charset=GBK" %>
<html>
<head>
<title>AJAX提交页面</title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<script type="text/javascript" src="ajax.js"></script>
   <script type="text/javascript">
   function doso(){
     var url = "actAction.do";
     var s="武晓强斯蒂芬34-*(&_(*!$^_*!&#!^$+!*#&&";
     s=encodeURIComponent(s);      //转换特殊字符
     var parameter ="name="+s+"&email=abc@abc.com&www=http://wxq594808632.blog.163.com/";
     var method = "POST";
     function callBack(text){           //回调函数
      alert("调用成功!\n名字为:"+text);
     }
   new Ajax().ajaxRequest(url,parameter,method,callBack);     //调用方法发送Request
   }
   </script>
</head>
<body>
<input type="button" value="提交" onclick="doso()"/>
   </body>
</html>

 

java类

ActAction.java

package ajaxpost;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.Action;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.io.PrintWriter;

public class ActAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws
            UnsupportedEncodingException {
        //设置字符编码返回的编码
        response.setContentType("text/html;charset=UTF-8");
        //接收字符的编码
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String www = request.getParameter("www");
        System.out.println(email);
        System.out.println(name);
        System.out.println(www);
     //   out.print(name+"\n"+email+"\n"+www);
        out.print(name);         //返回值
        return null;
    }
}

最重要滴

ajax.js

我用别人的。感谢这位大哥。。

/*
author zhangshuling
email 
zhangshuling1214@126.com
*/
function  Ajax(){
    var _xmlHttp = null;
 this.createXMLHttpRequest = function(){
  try{
   if (window.ActiveXObject) {                                                     
    _xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");                                     
   }                                                                               
   else if (window.XMLHttpRequest) {                                                   
    _xmlHttp = new XMLHttpRequest();                                               
   }
  }catch(e){
     alert(e.name +" : " + e.message);
  }
 }
 
 this.backFunction = function(_backFunction){
  if(_xmlHttp.readyState == 4) {
   if(_xmlHttp.status == 200) {
    _backFunction(_xmlHttp.responseText);//这里可以设置返回类型
   }
  }
   _xmlHttp.onreadystatechange = null;
 }

 this.doPost = function(_url,_parameter,_backFunction){
     try{
      _xmlHttp.open("POST",_url, false);
   _xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   _xmlHttp.send(_parameter);
   }catch(e){
    alert(e.name +" : " + e.message);
     }
 }
 
 this.doGet = function(_url,_parameter,_backFunction){
    try{
        var _random = Math.round(Math.random()*10000);
        _xmlHttp.open("GET", (_url+"?random=" +_random +"&" + _parameter), false);
     _xmlHttp.send(null);
   }catch(e){
      alert(e.name +" : " + e.message);
   }
 }
 
    this.ajaxRequest = function(_url,_parameter,_method,_backFunction){
          try{
            this.createXMLHttpRequest();
         if(_method.toLowerCase() == "post"){
            this.doPost(_url,_parameter,_backFunction);
         }else{
            this.doGet(_url,_parameter,_backFunction); 
         }
         try{
           _xmlHttp.onreadystatechange = this.backFunction(_backFunction);
         }catch(err){
            //??????IE?????????????????
         }
      }catch(e){
      alert(e.name +" : " + e.message);
   }
     }

}

/*
 var url = "ajax.do";
 var parameter = "parameter=parameter";
 var method = "post"
 
 function callBack(text){
  ....
 }
 
 new Ajax().ajaxRequest(url,parameter,method,callBack);

*/

 

经过本人FF,IE6,IE7,测试。完全好用


文章来源:http://wxq594808632.blog.163.com/blog/static/109079755200923121054225
posted @ 2009-03-31 14:11 武志强 阅读(826) | 评论 (0)编辑 收藏

import java.io.IOException;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.File;
import javax.imageio.ImageIO;

public class Img2 {
//读取远程url图片,得到宽高
    public int[] returnImgWH(String imgurl) {
        boolean b=false;
        try {
            //实例化url
            URL url = new URL(imgurl);
            //载入图片到输入流
            java.io.BufferedInputStream bis = new BufferedInputStream(url.openStream());
            //实例化存储字节数组
            byte[] bytes = new byte[100];
            //设置写入路径以及图片名称
            OutputStream bos = new FileOutputStream(new File( "C:\\thetempimg.gif"));
            int len;
            while ((len = bis.read(bytes)) > 0) {
                bos.write(bytes, 0, len);
            }
            bis.close();
            bos.flush();
            bos.close();
            //关闭输出流
            b=true;
        } catch (Exception e) {
            //如果图片未找到
            b=false;
        }
        int[] a = new int[2];
        if(b){    //图片存在
            //得到文件
            java.io.File file = new java.io.File("C:\\thetempimg.gif");
            BufferedImage bi = null;
            try {
                //读取图片
                bi = javax.imageio.ImageIO.read(file);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            a[0] = bi.getWidth(); //获得 宽度
            a[1] = bi.getHeight(); //获得 高度
            //删除文件
            file.delete();
        }else{     //图片不存在
            a=null;
        }
       return a;

    }

    public static void main(String[] args) {
        Img2 i = new Img2();
        int[] a=i.returnImgWH("http://www.baidu.com/img/baidu_logo.gif");
        if(a==null){
            System.out.println("图片未找到!");
        }else{
            System.out.println("宽为" + a[0]);
            System.out.println("高为" + a[1]);
        }
    }
}


文章来源:http://wxq594808632.blog.163.com/blog/static/10907975520092274458465
posted @ 2009-03-27 16:05 武志强 阅读(2335) | 评论 (0)编辑 收藏

如题

默认排序方式为asc,可省略...

select   *   from   table   order   by   t1   desc,   t2   desc  ,   t3 desc;


文章来源:http://wxq594808632.blog.163.com/blog/static/109079755200922444356457
posted @ 2009-03-24 16:44 武志强 阅读(159) | 评论 (0)编辑 收藏

 function jsTrim(value)
       {
              var reg=/^\S$/;
              if (!value) return "";
              if(value.length==0)
                     return value;
              else
              {
                     var lp,rp;
                     lp=0;rp=value.length-1;
                     while ((value.charAt(lp)==" "||(value.charCodeAt(lp)<128?(reg.test(value.charAt(lp))==false?true:false):false)||value.charAt(rp)==" "||(value.charCodeAt(rp)<128?(reg.test(value.charAt(rp))==false?true:false):false))&&rp>=lp)
                     {
                            if (value.charAt(lp)==" "||value.charCodeAt(lp)<128?(reg.test(value.charAt(lp))==false?true:false):false)
                                   lp++;
                            if (value.charAt(rp)==" "||value.charCodeAt(rp)<128?(reg.test(value.charAt(rp))==false?true:false):false)
                                   rp--;
                     }
                     if(lp>rp)
                            return "";
                     else
                            return (value.substring(lp,rp+1));

              }
       }


文章来源:http://wxq594808632.blog.163.com/blog/static/10907975520092205931780
posted @ 2009-03-20 17:10 武志强 阅读(975) | 评论 (0)编辑 收藏

 

引用

邵波的空间Java实现给图片添加水印
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import com.sun.image.codec.jpeg.*;

public class WaterMark ...{
/** *//**
* 给图片添加水印
* @param filePath 需要添加水印的图片的路径
* @param markContent 水印的文字
* @param markContentColor 水印文字的颜色
* @param qualNum 图片质量
* @return
*/
public boolean createMark(String filePath,String markContent,Color markContentColor,float qualNum,String watermark)
...{
ImageIcon imgIcon=new ImageIcon(filePath);
Image theImg =imgIcon.getImage();
int width=theImg.getWidth(null);
int height= theImg.getHeight(null);
//ImageIcon waterIcon=new ImageIcon(watermark);
//Image waterImg =waterIcon.getImage();
BufferedImage bimage = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
Graphics2D g=bimage.createGraphics();
g.setColor(markContentColor);
g.setBackground(Color.white);
g.drawImage(theImg, 0, 0, null );
//g.drawImage(waterImg, width*2, height, null );
g.drawString(markContent,width-100,height-30); //添加水印的文字和设置水印文字出现的内容
g.dispose();
try...{
FileOutputStream out=new FileOutputStream(filePath);
JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(qualNum, true);
encoder.encode(bimage, param);
out.close();
}catch(Exception e)
...{ return false; }
return true;
}
public static void main(String arg[])
...{
WaterMark wk=new WaterMark();
if(wk.createMark("D:\1.jpg","Welcome!",Color.WHITE,70f,""))...{
System.out.println("制作成功");
}else...{
System.out.println("失败了!");
}
}
}


文章来源:http://wxq594808632.blog.163.com/blog/static/109079755200921911832219
posted @ 2009-03-19 13:19 武志强 阅读(230) | 评论 (0)编辑 收藏

 

引用

邵波的空间如何防止同一个账户被多个人同时登陆?

1.用session超时,session为null就表示下线了      
     
  2.也可以采用数据库中设置     临时表     来处理      
  一个用户登陆时向表中插进一条记录,用户离开时候删除该记录      
  如想统计在线人数,简单地执行      
  select     count(*)     from     table...     即可      
     
  3.application对象中可以记住现在的人数,application的生命周期和服务器的生命周期一样长。      
     
  4.还有一种方法要用到一个文件global.jsa     ,方法是(在JSP中)是sessionDestroy(),其中它是以session对象为参数的。还有要把global.jsa文件必须房子和JSP程序相同的文件目录内才行。      
     
  5.网页自动刷新的代码是:      
  在文件头部加上      
  <meta     http-equiv="refresh"     content="15">      
  刷新间隔时间是15秒      
     
     
  6.在session中加入监听类,类的示例代码如下:      

onLineUser.java-------------------------------------------------------------------------------------------

package com.shaobo.struts.action;

import javax.servlet.http.*;
import javax.servlet.*;
import java.util.*;

public class onLineUser implements HttpSessionBindingListener {
 public onLineUser() {
 }

 private Vector users = new Vector();

 public int getCount() {
  users.trimToSize();
  return users.capacity();
 }

 public boolean existUser(String userName) {
  users.trimToSize();
  boolean existUser = false;
  for (int i = 0; i < users.capacity(); i++) {
   if (userName.equals((String) users.get(i))) {
    existUser = true;
    break;
   }
  }
  return existUser;
 }

 public boolean deleteUser(String userName) {
  users.trimToSize();
  if (existUser(userName)) {
   int currUserIndex = -1;
   for (int i = 0; i < users.capacity(); i++) {
    if (userName.equals((String) users.get(i))) {
     currUserIndex = i;
     break;
    }
   }
   if (currUserIndex != -1) {
    users.remove(currUserIndex);
    users.trimToSize();
    return true;
   }
  }
  return false;
 }

 public Vector getOnLineUser() {
  return users;
 }

 public void valueBound(HttpSessionBindingEvent e) {
  users.trimToSize();
  if (!existUser(e.getName())) {
   users.add(e.getName());
   System.out.print(e.getName() + "\t登入到系统\t"
     + (new Date()));
   System.out.println("在线用户数为:" + getCount());
  } else
   System.out.println(e.getName() + "已经存在");
 }

 public void valueUnbound(HttpSessionBindingEvent e) {
  users.trimToSize();
  String userName = e.getName();
  deleteUser(userName);
  System.out.print(userName + "\t退出系统\t" + (new Date()));
  System.out.println("在线用户数为:" + getCount());
 }
}

login.jsp--------------------------------------------------------------------------------------------

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<jsp:useBean id="onlineuser" class="com.shaobo.struts.action.onLineUser"
 scope="application" />
<html>
 <head>
 </head>
 <body onUnload="postMessage()">
  <center>
   <p>
   <h1>
    登陆成功,欢迎访问
   </h1>
   </p>
  </center>
  <%
  session = request.getSession(false);
  %>
  <%
   String username = request.getParameter("username");
   if (onlineuser.existUser(username)) {
    out.println("用户<font color=red>" + username
    + "</font>已经登陆!");
   } else {
    session.setMaxInactiveInterval(50); //Sesion有效时长,以秒为单位      
    session.setAttribute(username, onlineuser);
    out.println("欢迎新用户:<font color=red>" + username
    + "</font>登陆到系统!");
   }
   out.println("<br>当前在线用户人数:<font color=red>"
     + onlineuser.getCount() + "</font><br>");
   String ip = request.getRemoteAddr();
   out.println("<br>IP:<font color=red>" + ip + "</font><br>");
   Vector vt = onlineuser.getOnLineUser();
   Enumeration e = vt.elements();
   out.println("在线用户列表");
   out.println("<table border=1>");
   out.println("<tr><td>用户名</td></tr>");
   while (e.hasMoreElements()) {
    out.println("<tr><td>");
    out.println((String) e.nextElement() + "<br>");
    out.println("</td></tr>");
   }
   out.println("</table>");
  %>
  <center>
   <p>
   </p>
   [
   <a href="javascript:window.close()">关闭窗口</a>]
   <%
    out.println("<p><a href='index.jsp'>退出系统</a></p>");
   %>
  </center>
  <Script>      
              function postMessage(){                                                                  
                 <%onlineuser.deleteUser(request.getParameter("username"));%>      
            }      
  </Script>
 </body>
</html>

欢迎光临邵波的空间` http://blog.sina.com.cn/shaobolive

QQ:343269876


文章来源:http://wxq594808632.blog.163.com/blog/static/10907975520092191192874
posted @ 2009-03-19 13:19 武志强 阅读(789) | 评论 (0)编辑 收藏
一.获得控制台用户输入的信息

/** *//**获得控制台用户输入的信息
     * @return
     * @throws IOException
     */
    public String getInputMessage() throws IOException...{
        System.out.println("请输入您的命令∶");
        byte buffer[]=new byte[1024];
        int count=System.in.read(buffer);
        char[] ch=new char[count-2];//最后两位为结束符,删去不要
        for(int i=0;i<count-2;i++)
            ch[i]=(char)buffer[i];
        String str=new String(ch);
        return str;
    }
可以返回用户输入的信息,不足之处在于不支持中文输入,有待进一步改进。

二.复制文件

1.以文件流的方式复制文件

/** *//**以文件流的方式复制文件
     * @param src 文件源目录
     * @param dest 文件目的目录
     * @throws IOException 
     */
    public void copyFile(String src,String dest) throws IOException...{
        FileInputStream in=new FileInputStream(src);
        File file=new File(dest);
        if(!file.exists())
            file.createNewFile();
        FileOutputStream out=new FileOutputStream(file);
        int c;
        byte buffer[]=new byte[1024];
        while((c=in.read(buffer))!=-1)...{
            for(int i=0;i<c;i++)
                out.write(buffer[i]);       
        }
        in.close();
        out.close();
    }
该方法经过测试,支持中文处理,并且可以复制多种类型,比如txt,xml,jpg,doc等多种格式

三.写文件

1.利用PrintStream写文件

/** *//**
     * 文件输出示例
     */
    public void PrintStreamDemo()...{
        try ...{
            FileOutputStream out=new FileOutputStream("D:/test.txt");
            PrintStream p=new PrintStream(out);
            for(int i=0;i<10;i++)
                p.println("This is "+i+" line");
        } catch (FileNotFoundException e) ...{
            e.printStackTrace();
        }
    }
2.利用StringBuffer写文件

public void StringBufferDemo() throws IOException......{
        File file=new File("/root/sms.log");
        if(!file.exists())
            file.createNewFile();
        FileOutputStream out=new FileOutputStream(file,true);       
        for(int i=0;i<10000;i++)......{
            StringBuffer sb=new StringBuffer();
            sb.append("这是第"+i+"行:前面介绍的各种方法都不关用,为什么总是奇怪的问题 ");
            out.write(sb.toString().getBytes("utf-8"));
        }       
        out.close();
    }
该方法可以设定使用何种编码,有效解决中文问题。

四.文件重命名


    /** *//**文件重命名
     * @param path 文件目录
     * @param oldname  原来的文件名
     * @param newname 新文件名
     */
    public void renameFile(String path,String oldname,String newname)...{
        if(!oldname.equals(newname))...{//新的文件名和以前文件名不同时,才有必要进行重命名
            File oldfile=new File(path+"/"+oldname);
            File newfile=new File(path+"/"+newname);
            if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名
                System.out.println(newname+"已经存在!");
            else...{
                oldfile.renameTo(newfile);
            }
        }        
    }五.转移文件目录


转移文件目录不等同于复制文件,复制文件是复制后两个目录都存在该文件,而转移文件目录则是转移后,只有新目录中存在该文件。

    /** *//**转移文件目录
     * @param filename 文件名
     * @param oldpath 旧目录
     * @param newpath 新目录
     * @param cover 若新目录下存在和转移文件具有相同文件名的文件时,是否覆盖新目录下文件,cover=true将会覆盖原文件,否则不操作
     */
    public void changeDirectory(String filename,String oldpath,String newpath,boolean cover)...{
        if(!oldpath.equals(newpath))...{
            File oldfile=new File(oldpath+"/"+filename);
            File newfile=new File(newpath+"/"+filename);
            if(newfile.exists())...{//若在待转移目录下,已经存在待转移文件
                if(cover)//覆盖
                    oldfile.renameTo(newfile);
                else
                    System.out.println("在新目录下已经存在:"+filename);
            }
            else...{
                oldfile.renameTo(newfile);
            }
        }      
    }



六.读文件

1.利用FileInputStream读取文件


    /** *//**读文件
     * @param path
     * @return
     * @throws IOException
     */
    public String FileInputStreamDemo(String path) throws IOException...{
        File file=new File(path);
        if(!file.exists()||file.isDirectory())
            throw new FileNotFoundException();
        FileInputStream fis=new FileInputStream(file);
        byte[] buf = new byte[1024];
        StringBuffer sb=new StringBuffer();
        while((fis.read(buf))!=-1)...{
            sb.append(new String(buf));   
            buf=new byte[1024];//重新生成,避免和上次读取的数据重复
        }
        return sb.toString();
    }


2.利用BufferedReader读取

在IO操作,利用BufferedReader和BufferedWriter效率会更高一点

    /** *//**读文件
     * @param path
     * @return
     * @throws IOException
     */
    public String BufferedReaderDemo(String path) throws IOException...{
        File file=new File(path);
        if(!file.exists()||file.isDirectory())
            throw new FileNotFoundException();
        BufferedReader br=new BufferedReader(new FileReader(file));
        String temp=null;
        StringBuffer sb=new StringBuffer();
        temp=br.readLine();
        while(temp!=null)...{
            sb.append(temp+" ");
            temp=br.readLine();
        }
        return sb.toString();
    }


3.利用dom4j读取xml文件

    /** *//**从目录中读取xml文件
     * @param path 文件目录
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public Document readXml(String path) throws DocumentException, IOException...{
        File file=new File(path);
        BufferedReader bufferedreader = new BufferedReader(new FileReader(file));
        SAXReader saxreader = new SAXReader();
        Document document = (Document)saxreader.read(bufferedreader);
        bufferedreader.close();
        return document;
    }


七.创建文件(文件夹)

1.创建文件夹  /** *//**创建文件夹
     * @param path  目录
     */
    public void createDir(String path)...{
        File dir=new File(path);
        if(!dir.exists())
            dir.mkdir();
    }
2.创建新文件 /** *//**创建新文件
     * @param path 目录
     * @param filename 文件名
     * @throws IOException
     */
    public void createFile(String path,String filename) throws IOException...{
        File file=new File(path+"/"+filename);
        if(!file.exists())
            file.createNewFile();
    }
八.删除文件(目录)

1.删除文件     /** *//**删除文件
     * @param path 目录
     * @param filename 文件名
     */
    public void delFile(String path,String filename)...{
        File file=new File(path+"/"+filename);
        if(file.exists()&&file.isFile())
            file.delete();
    }
2.删除目录
要利用File类的delete()方法删除目录时,必须保证该目录下没有文件或者子目录,否则删除失败,因此在实际应用中,我们要删除目录,必须利用递归删除该目录下的所有子目录和文件,然后再删除该目录。  /** *//**递归删除文件夹
     * @param path
     */
    public void delDir(String path)...{
        File dir=new File(path);
        if(dir.exists())...{
            File[] tmp=dir.listFiles();
            for(int i=0;i<tmp.length;i++)...{
                if(tmp[i].isDirectory())...{
                    delDir(path+"/"+tmp[i].getName());
                }
                else...{
                    tmp[i].delete();
                }
            }
            dir.delete();
        }
    }

文章来源:http://wxq594808632.blog.163.com/blog/static/109079755200921911749952
posted @ 2009-03-19 13:18 武志强 阅读(213) | 评论 (0)编辑 收藏
仅列出标题  下一页