目前分類:JAVA (866)

瀏覽方式: 標題列表 簡短摘要

未命名  

import java.io.BufferedReader;
import java.io.IOException;

shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

  利用google、百度搜索引擎的搜索規則中的兩條:關鍵字搜索和inurl搜索。

     inurl搜索:就是你所要搜索的網址中本身帶有的關鍵字,比如http://fecbob.pixnet.net/index.asp ,這個網址就含有index.asp這樣的關鍵字,在搜索引擎中填寫規則是 inurl:index.asp,這是收集網址的關鍵,因為很多網址本身會帶有特定的資訊,比如軟體發佈的網頁網址資訊中多含有 publish、submit、tuijian這樣的資訊,如http://fecbob.pixnet.net/home.asp,這樣的網址多是發佈資訊的網頁,在結合網頁中本身可能含有的關鍵字,就可以用搜索引擎搜索出結果,然後我們利用程式將結果取回,對HTML頁面進行分析,去除沒有用的資訊,將有用的網址資訊寫入文件或者數據庫,就可以給其他應用程式或者人來使用了。

shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

未命名  

程式碼下載


shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

未命名  

程式碼下載


shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

private static class MonitoringThread implements Runnable {     
 private Logger log = Logger.getLogger(MonitoringThread.class);   
 

shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

public static void main(String[] args){        try {            BufferedReader br=new BufferedReader(new FileReader(new File("e:/ime.txt")));            OutputStream os=new FileOutputStream(new File("e:/sql.txt"));                        byte[] buf2={13,10};//换行            String line="";            while((line=br.readLine())!=null){                String[] arr=line.split(" ");                int len=arr.length;                String spell="";                String initial="";                for(int i=3;i<len;i++){                    spell+=arr[i];                    initial+=arr[i].charAt(0);                }                String insertSql="insert into match_word(word,initial,spell,store_state,sync_state,mark_times, use_times, state) values('"+arr[0]+"','"+initial+"','"+spell+"', '已入库', '已同步',0, 0,'正常');";                os.write(insertSql.getBytes());                os.write(buf2);            }            br.close();            os.flush();            os.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }


shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

public static List<String> getImgStr(String htmlStr){          String img="";          Pattern p_image;          Matcher m_image;          List<String> pics = new ArrayList<String>();         String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址          p_image = Pattern.compile                (regEx_img,Pattern.CASE_INSENSITIVE);         m_image = p_image.matcher(htmlStr);       while(m_image.find()){              img = img + "," + m_image.group();              Matcher m  = Pattern.compile("src=\"?(.*?)                         (\"|>|\\s+)").matcher(img); //匹配src           while(m.find()){              pics.add(m.group(1));           }       }             return pics;      }   

 

public static final Pattern PATTERN  = Pattern.compile("<img\\s+(?:[^>]*)src\\s*=\\s*([^>]+)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);                         public static List getImgSrc(String html) {                Matcher matcher = PATTERN.matcher(html);                List list = new ArrayList();                while (matcher.find()) {                  String group = matcher.group(1);                  if (group == null) {                    continue;                  }                  // 这里可能还需要更复杂的判断,用以处理src="...."内的一些转义符                  if (group.startsWith("'")) {                    list.add(group.substring(1, group.indexOf("'", 1)));                  } else if (group.startsWith("\"")) {                    list.add(group.substring(1, group.indexOf("\"", 1)));                  } else {                    list.add(group.split("\\s")[0]);                  }                }                return list;              }

shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

package com.gemron;import java.util.ArrayList;import java.util.List;public class domainGen {    public static void main(String[] args) {        List<String> list = new ArrayList<String>();        int length = 2;        appendDomain(list, "", length, false);        for (String string : list) {            System.out.println(string);        }    }    public static void appendDomain(List<String> b, String pre, int length,            boolean haveNum) {        int i = 48;        if (!haveNum) {            i = 97;        }        length--;        for (; i < 123; i++) {            String str = Character.toString((char) i);            String res = pre + str;            if (length == 0) {                b.add(res);            } else {                appendDomain(b, res, length, haveNum);            }            if (i == 57) {                i = 96;            }        }    }    public static List<String> getDomainList(int length, String isHaveNum) {        boolean haveNum = "y".equals(isHaveNum.toLowerCase());        List<String> list = new ArrayList<String>();        appendDomain(list, "", length, haveNum);        return list;    }}

 

 

shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

package net.szh.zip;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FilterInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.SequenceInputStream;import java.util.ArrayList;import java.util.Enumeration;import java.util.List;import java.util.zip.CRC32;import java.util.zip.CheckedOutputStream;import java.util.zip.Checksum;//import javax.rmi.CORBA.Util;//import java.util.zip.ZipEntry;//import java.util.zip.ZipOutputStream;import org.apache.tools.zip.ZipEntry;import org.apache.tools.zip.ZipOutputStream;import org.apache.tools.zip.ZipFile;public class ZipCompress {    static final int BUFFER = 8192;    private File zipFile;    public ZipCompress(String pathName) {        zipFile = new File(pathName);    }    public void Compress(String srcPathName) {        File file = new File(srcPathName);        if (!file.exists()) {            throw new RuntimeException(srcPathName + "不存在");        }        try {            FileOutputStream fos = new FileOutputStream(zipFile);            CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32());            ZipOutputStream zos =new ZipOutputStream(cos);                        BufferedOutputStream bos = new BufferedOutputStream(zos);            ArrayList<String> list=new ArrayList<String>();            list.add("d:/安装系统.exe");            list.add("d:/FeiQ.exe");             list.add("e:/jk.txt");//添加你要压缩的文件目录            for(String string:list){                BufferedReader in = new BufferedReader(new FileReader(string));                int i=0;                zos.putNextEntry(new ZipEntry(string));                while((i=in.read())!=-1){                    zos.write(i);                }                zos.flush();                in.close();            }                                    String basedir = "";            Compress(file, zos, basedir);            zos.close();        } catch (Exception e) {            throw new RuntimeException(e);        }    }    private void Compress(File file, ZipOutputStream zos, String basedir) {        if (file.isDirectory()) {            System.out.println("压缩" + basedir + file.getName()+"成功");            this.CompressDirectory(file, zos, basedir);        } else {            System.out.println("压缩" + basedir + file.getName()+"成功");            this.CompressFile(file, zos, basedir);        }    }    private void CompressDirectory(File dir, ZipOutputStream zos, String basedir) {        if (!dir.exists()) {            return;        }        File[] files = dir.listFiles();        for (int i = 0; i < files[i].length(); i++) {            Compress(files[i], zos, basedir + dir.getName() + "/");        }    }    private void CompressFile(File file, ZipOutputStream out, String basedir) {        if (!file.exists()) {            return;        }        try {            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));            ZipEntry ze = new ZipEntry(basedir + file.getName());            out.putNextEntry(ze);            int count;            byte[] data = new byte[BUFFER];            while ((count = bis.read(data, 0, BUFFER)) != -1) {                out.write(data, 0, BUFFER);            }            bis.close();        } catch (Exception e) {            throw new RuntimeException(e);        }    }    public static void main(String args[]) {        ZipCompress zc = new ZipCompress("d:/java.zip");        zc.Compress("d:/");        System.out.println("OK/......");    }}//public class ZipCompress{//    public static void main(String args[]) throws IOException{//        File f1 = new File("d:/jk.txt");//        File f2 = new File("d:/kj.txt");//        File f3 = new File("d:/jj.txt");//        FileInputStream fis = new FileInputStream(f1);//        FileInputStream fis1 = new FileInputStream(f2);//        //        InputStream sis = new SequenceInputStream(fis, fis1);//        //        InputStreamReader isr = new InputStreamReader(sis);//        //        FileOutputStream fos = new FileOutputStream(f3, true);//        //        OutputStreamWriter osw = new OutputStreamWriter(fos);//        //        int c;//        while((c=isr.read())!=-1){//            osw.write((char)c);//        }//        System.out.println("ok....");//        isr.close();//        osw.close();//        //    }//}/**   两个文件内容汇总到另外一个文件中*/

 

 

shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

package k.barcode;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.poifs.filesystem.POIFSFileSystem;import org.apache.poi.ss.usermodel.ClientAnchor;import org.apache.poi.ss.usermodel.CreationHelper;import org.apache.poi.ss.usermodel.Drawing;import org.apache.poi.ss.usermodel.Picture;import org.apache.poi.ss.usermodel.Workbook;import org.apache.poi.util.IOUtils;import org.krysalis.barcode4j.impl.code39.Code39Bean;import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;import org.krysalis.barcode4j.tools.UnitConv;public class InsExcel {    private POIFSFileSystem fs;    private HSSFWorkbook wb;    private HSSFSheet sheet;    private HSSFRow row;    private FileInputStream input;    private String[] excleTitle;    public static void main(String[] args) {        //生成条码        String bcVal = InsExcel.makeBarcodeValue();        //生成条码图片        String bcPath = InsExcel.makeBarcode(bcVal);        //插入excel        InsExcel.insBarcodeInExcel(bcPath);    }        //生成条码值    public static String makeBarcodeValue(){        return "A"+System.currentTimeMillis();    }        //生成条码文件至临时目录,并返回生成图片的路径信息    public static String makeBarcode(final String barcodeValue){        //存放条码图片的路径        final String barcodePicPath = "d:\\barcode\\";        try {            //Create the barcode bean            Code39Bean bean = new Code39Bean();                        final int dpi = 150;                        //Configure the barcode generator            bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar                                                              //width exactly one pixel            bean.setWideFactor(3);            bean.doQuietZone(false);                        //Open output file            File outputFile = new File(barcodePicPath+barcodeValue+".png");            OutputStream out = new FileOutputStream(outputFile);            try {                //Set up the canvas provider for monochrome JPEG output                 BitmapCanvasProvider canvas = new BitmapCanvasProvider(                        out, "image/png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);                            //Generate the barcode                bean.generateBarcode(canvas, barcodeValue);                            //Signal end of generation                canvas.finish();            } finally {                out.close();            }        } catch (Exception e) {            e.printStackTrace();        }                return barcodePicPath+barcodeValue+".png";    }        public static void insBarcodeInExcel(String barcodePic){        FileInputStream input = null;        try {            input = new FileInputStream(new File("d:\\base.xls"));// excelPath,Excel            // 文件 的绝对路径            POIFSFileSystem fs = new POIFSFileSystem(input);            HSSFWorkbook wb = new HSSFWorkbook(fs);            HSSFSheet sheet = wb.getSheetAt(1);            HSSFRow row = sheet.getRow(0);// 得到标题的内容对象。            System.out.println(row.getCell(15).toString());            InputStream inputStream = new FileInputStream(barcodePic);            byte[] bytes = IOUtils.toByteArray(inputStream);            int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);            inputStream.close();            CreationHelper helper = wb.getCreationHelper();            Drawing drawing = sheet.createDrawingPatriarch();            ClientAnchor anchor = helper.createClientAnchor();            anchor.setCol1(15);            anchor.setRow1(0);            Picture pict = drawing.createPicture(anchor, pictureIdx);            pict.resize();            FileOutputStream fileOut = new FileOutputStream("d:\\base.xls");            wb.write(fileOut);            fileOut.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                if (input != null) {                    input.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }}


shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

最近一直在开发一个用于自动发帖的工具,用HttpClient模拟客户端浏览器注册发帖。但是碰到了图形验证码的问题了,对单数字的验证码,通过一些OCR引擎,如:tesseract,AspriseOCR很容易解决问题。但碰到如CSDN论坛这中图形验证码就比较麻烦,必须先通过预处理。使图象二值化,黑白灰度,增加亮度。我的代码如下: package myfilter;import java.io.*;import java.awt.image.*;import java.awt.geom.AffineTransform;import java.awt.color.ColorSpace;import java.awt.image.ConvolveOp;import java.awt.image.Kernel;import java.awt.image.BufferedImage;import javax.imageio.ImageIO;import java.awt.Toolkit;import java.awt.Image;public class MyImgFilter {BufferedImage image;private int iw, ih;private int[] pixels;public MyImgFilter(BufferedImage image) {this.image = image;iw = image.getWidth();ih = image.getHeight();pixels = new int[iw * ih];}public BufferedImage changeGrey() {PixelGrabber pg = new PixelGrabber(image.getSource(), 0, 0, iw, ih, pixels,0, iw);try {pg.grabPixels();} catch (InterruptedException e) {e.printStackTrace();}// 设定二值化的域值,默认值为100int grey = 100;// 对图像进行二值化处理,Alpha值保持不变ColorModel cm = ColorModel.getRGBdefault();for (int i = 0; i < iw * ih; i++) {int red, green, blue;int alpha = cm.getAlpha(pixels[i]);if (cm.getRed(pixels[i]) > grey) {red = 255;} else {red = 0;}if (cm.getGreen(pixels[i]) > grey) {green = 255;} else {green = 0;}if (cm.getBlue(pixels[i]) > grey) {blue = 255;} else {blue = 0;}pixels[i] = alpha << 24 | red << 16 | green << 8 | blue; //通过移位重新构成某一点像素的RGB值}// 将数组中的象素产生一个图像Image tempImg=Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(iw,ih, pixels, 0, iw));image = new BufferedImage(tempImg.getWidth(null),tempImg.getHeight(null), BufferedImage.TYPE_INT_BGR );image.createGraphics().drawImage(tempImg, 0, 0, null);return image;}public BufferedImage getMedian() {PixelGrabber pg = new PixelGrabber(image.getSource(), 0, 0, iw, ih,pixels,0, iw);try {pg.grabPixels();} catch (InterruptedException e) {e.printStackTrace();}// 对图像进行中值滤波,Alpha值保持不变ColorModel cm = ColorModel.getRGBdefault();for (int i = 1; i < ih - 1; i++) {for (int j = 1; j < iw - 1; j++) {int red, green, blue;int alpha = cm.getAlpha(pixels[i * iw + j]);// int red2 = cm.getRed(pixels[(i - 1) * iw + j]);int red4 = cm.getRed(pixels[i * iw + j - 1]);int red5 = cm.getRed(pixels[i * iw + j]);int red6 = cm.getRed(pixels[i * iw + j + 1]);// int red8 = cm.getRed(pixels[(i + 1) * iw + j]);// 水平方向进行中值滤波if (red4 >= red5) {if (red5 >= red6) {red = red5;} else {if (red4 >= red6) {red = red6;} else {red = red4;}}} else {if (red4 > red6) {red = red4;} else {if (red5 > red6) {red = red6;} else {red = red5;}}}int green4 = cm.getGreen(pixels[i * iw + j - 1]);int green5 = cm.getGreen(pixels[i * iw + j]);int green6 = cm.getGreen(pixels[i * iw + j + 1]);// 水平方向进行中值滤波if (green4 >= green5) {if (green5 >= green6) {green = green5;} else {if (green4 >= green6) {green = green6;} else {green = green4;}}} else {if (green4 > green6) {green = green4;} else {if (green5 > green6) {green = green6;} else {green = green5;}}}// int blue2 = cm.getBlue(pixels[(i - 1) * iw + j]);int blue4 = cm.getBlue(pixels[i * iw + j - 1]);int blue5 = cm.getBlue(pixels[i * iw + j]);int blue6 = cm.getBlue(pixels[i * iw + j + 1]);// int blue8 = cm.getBlue(pixels[(i + 1) * iw + j]);// 水平方向进行中值滤波if (blue4 >= blue5) {if (blue5 >= blue6) {blue = blue5;} else {if (blue4 >= blue6) {blue = blue6;} else {blue = blue4;}}} else {if (blue4 > blue6) {blue = blue4;} else {if (blue5 > blue6) {blue = blue6;} else {blue = blue5;}}}pixels[i * iw +j] = alpha << 24 | red << 16 | green << 8 | blue;}}// 将数组中的象素产生一个图像Image tempImg=Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(iw,ih, pixels, 0, iw));image = new BufferedImage(tempImg.getWidth(null),tempImg.getHeight(null), BufferedImage.TYPE_INT_BGR );image.createGraphics().drawImage(tempImg, 0, 0, null);return image;}public BufferedImage getGrey() {ColorConvertOp ccp=new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);return image=ccp.filter(image,null);}//Brighten using a linear formula that increases all color valuespublic BufferedImage getBrighten() {RescaleOp rop=new RescaleOp(1.25f, 0, null);return image=rop.filter(image,null);}//Blur by "convolving" the image with a matrixpublic BufferedImage getBlur() {float[] data = {.1111f, .1111f, .1111f,.1111f, .1111f, .1111f,.1111f, .1111f, .1111f, };ConvolveOp cop = new ConvolveOp(new Kernel(3, 3, data));return image=cop.filter(image,null);}// Sharpen by using a different matrixpublic BufferedImage getSharpen() {float[] data = {0.0f, -0.75f, 0.0f,-0.75f, 4.0f, -0.75f,0.0f, -0.75f, 0.0f};ConvolveOp cop = new ConvolveOp(new Kernel(3, 3, data));return image=cop.filter(image,null);}// 11) Rotate the image 180 degrees about its center pointpublic BufferedImage getRotate() {AffineTransformOp atop=new AffineTransformOp(AffineTransform.getRotateInstance(Math.PI,image.getWidth()/2,image.getHeight()/2),AffineTransformOp.TYPE_NEAREST_NEIGHBOR);return image=atop.filter(image,null);}public BufferedImage getProcessedImg(){return image;}public static void main(String[] args) throws IOException {FileInputStream fin=new FileInputStream(args[0]);BufferedImage bi=ImageIO.read(fin);MyImgFilter flt=new MyImgFilter(bi);flt.changeGrey();flt.getGrey();flt.getBrighten();bi=flt.getProcessedImg();String pname=args[0].substring(0,args[0].lastIndexOf("."));File file = new File(pname+".jpg");ImageIO.write(bi, "jpg", file);}}运行java myfilter.MyImgFilter t6.bmp,请确认图片t6.bmp与myfilter目录在同一目录下。顺便说一下,在JDK1.5下,ImageIO可以输出JPG,BMP,PNG三种格式图片,但不支持GIF图片输出。


shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

package userClient;import java.awt.CardLayout;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.io.File;import java.text.DateFormat;import java.util.Date;import javax.swing.*;import javax.swing.tree.*;import superuserclient.*;//class MyNode{                              //自定义的初始化树节点的数据对象的类//    private String values;             //声明values属性//    private String id;                 //用于确定节点的id属性//    public MyNode(String values ,String id){  //构造器//        this.values = values;                //设置values的值//        this.id = id;                       //设置id的值//    }//    public String toString (){             //复写toString 方法;返回values的值//        return this.values;                //    }//    public String getid(){return this.id;} //id 的get方法//}public class SuperUserClient extends JFrame {        /**     *      */    private static final long serialVersionUID = 703826588965541613L;    public String userId =null;//登录用户的学生号          public String getUserId() {        return userId;    }    public void setUserId(String userId) {        this.userId = userId;    }    //声明树的各个节点     private DefaultMutableTreeNode dmtnRoot = new DefaultMutableTreeNode(new MyNode("超级用户客户端","0"));//创建根节点     //创建一级节点     //private DefaultMutableTreeNode dmtn1 = new DefaultMutableTreeNode(new MyNode("借还管理","1"));       private DefaultMutableTreeNode dmtn1 = new DefaultMutableTreeNode(new MyNode("自行车管理","1"));     private DefaultMutableTreeNode dmtn2 = new DefaultMutableTreeNode(new MyNode("用户管理","2"));     private DefaultMutableTreeNode dmtn3 = new DefaultMutableTreeNode(new MyNode("系统","3"));    //创建二级节点     private DefaultMutableTreeNode dmtn11 = new DefaultMutableTreeNode(new MyNode("我的自行车","11"));     private DefaultMutableTreeNode dmtn12 = new DefaultMutableTreeNode(new MyNode("预定自行车","12"));     private DefaultMutableTreeNode dmtn13 = new DefaultMutableTreeNode(new MyNode("归还自行车","13"));     private DefaultMutableTreeNode dmtn14 = new DefaultMutableTreeNode(new MyNode("报修自行车","14"));     private DefaultMutableTreeNode dmtn21 = new DefaultMutableTreeNode(new MyNode("用户操作","21"));     private DefaultMutableTreeNode dmtn22 = new DefaultMutableTreeNode(new MyNode("用户信息反馈","22"));     private DefaultMutableTreeNode dmtn23 = new DefaultMutableTreeNode(new MyNode("用户信息提醒","23"));          private DefaultMutableTreeNode dmtn31 = new DefaultMutableTreeNode(new MyNode("密码修改","31"));     private DefaultMutableTreeNode dmtn32 = new DefaultMutableTreeNode(new MyNode("基本信息查询","32"));     private DefaultMutableTreeNode dmtn33 = new DefaultMutableTreeNode(new MyNode("退出","33"));          private DefaultTreeModel dtm = new DefaultTreeModel(dmtnRoot);//创建跟节点     private JTree jt = new JTree(dtm);//创建树状列表控件//     private JScrollPane jspz = new JScrollPane(jt);       //创建滚动窗口//     private JPanel jpy= new JPanel();                     //创建面板//     private JSplitPane jsp1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,jspz,jpy);//创建分割窗口,水平分割,jspz在左边,jpy在右边//              private javax.swing.JLabel jlb_up;     private javax.swing.JPanel jp_left;     private javax.swing.JPanel jp_up;     private javax.swing.JPanel jpy;     private javax.swing.JSplitPane jsp1;     private javax.swing.JScrollPane jspz;               CardLayout cl;           //声明卡片布局引用         //声明功能模块引用,(声明语句将在后面各模块的开发过程中逐一添加)          //////////-----------------------1、添加模块声明-----------------------------/////////             MyEquipment myequipment ;        //查询模块声明             EquipmentOrdered equipmentordered;//预定模块             EquipmentRequireMended equipmentrequiremended ;             PwdModify userpwdmodify;       //--------------------------------------------------------------               public SuperUserClient(){    //构造器        // this.userId = userId;         this.initComponents();  //初始化主窗体         this.initialJpy();     //初始化画板         this.initialPanel();  //初始化各功能模块对象         this.initialTree();     //初始化树列表控件         this.addListener(); //为节点注册监听器              }          public SuperUserClient(String user){    //构造器          this.userId = user;//          System.out.println("*************************************************"+userId);          this.initComponents();  //初始化主窗体          this.initialJpy();     //初始化画板          this.initialPanel();  //初始化各功能模块对象          this.initialTree();     //初始化树列表控件          this.addListener(); //为节点注册监听器                }          //2.6.2          public void initialPanel() {//初始化各功能模块                          //----------------------创建个功能模块实例------------------                 myequipment = new MyEquipment(userId);         equipmentordered = new EquipmentOrdered(userId);         equipmentrequiremended = new EquipmentRequireMended(userId);         userpwdmodify = new PwdModify(userId);         //---------------------------------------------------------     }            public void initialTree(){ //初始化树状列表控件的方法         dmtnRoot.add(dmtn1);                                             dmtn1.add(dmtn11);dmtn1.add(dmtn12);dmtn1.add(dmtn13);dmtn1.add(dmtn14);                    dmtnRoot.add(dmtn2);//将各节点添加到根节点         dmtn2.add(dmtn21);dmtn2.add(dmtn22);dmtn2.add(dmtn23);          dmtnRoot.add(dmtn3);//将各节点添加到根节点         dmtn3.add(dmtn31);dmtn3.add(dmtn32);dmtn3.add(dmtn33);             }          public void initialJpy(){                //将个功能模块添加到画板         jpy.setLayout(new CardLayout());    //将画板设置成卡片布局模式         cl = (CardLayout)jpy.getLayout();   //得到画板卡片布局模式的引用        // jpy.add(changepwdteacher, "changepwdteacher");             //---------------待添加-----------                                }//     //     public void initialJFrame(){       //设置窗体的标题,大小,及其可见性//         this.add(jsp1);jsp1.setDividerLocation(200);//将分割窗体添加到窗体,并设置分割窗体的位置//         jsp1.setDividerSize(4);       //设置分割窗体的宽度//         //         //String picPath = "d:" + File.separator + "workspace" + File.separator + "xs.jpg"; //         // Icon icon = new ImageIcon(picPath);//         // this.setIcon(icon);//          //         Image image = new ImageIcon("ico.gif").getImage();//加载窗体图标对象//         this.setIconImage(image); this.setTitle("用户客户端");//设置窗体的图标和标题//         Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();//得到屏幕的dimension(大小)值//         int centerX = screensize.width/2;//得到屏幕宽度的中间像素点//         int centerY = screensize.height/2;//得到屏幕高度得中间像素点//         int w =900;//本窗体宽度//         int h =650;//本窗体高度//         this.setBounds(centerX-w/2,centerY-h/2,w,h);//设置窗体出现在屏幕中央;//                                                        //setBounts:移动组件并调整其大小,使其符合新的有界矩形 r。由 r.x 和 r.y 指定组件的新位置,由 r.width 和 r.height 指定组件的新大小 //         this.setVisible(true);                         //设置窗体可见//        // this.setExtendedState(JFrame.MAXIMIZED_BOTH);//窗体全屏//         //     }               private void initComponents() {         Date now ;         DateFormat d1 = DateFormat.getDateTimeInstance();         now = new Date();          String str_now = d1.format(now);         this.setTitle("超级用户"+userId+"                                                     登录时间为:"+ str_now);         jp_up = new javax.swing.JPanel();         jlb_up = new javax.swing.JLabel();         jsp1 = new javax.swing.JSplitPane();         jp_left = new javax.swing.JPanel();                           /*************************************************************************          * 注意修改点          * ************************************************************************/         jspz = new JScrollPane(jt);       //创建滚动窗口         jpy = new javax.swing.JPanel();               // setBounds(300, 300, 900, 900);         jp_up.setBackground(new java.awt.Color(0, 51, 204));         jlb_up.setBackground(new java.awt.Color(0, 0, 204));         jlb_up.setFont(new java.awt.Font("宋体", 1, 36)); // NOI18N         jlb_up.setForeground(new java.awt.Color(0, 0, 204));         jlb_up.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);                          String picPath = System.getProperty("user.dir")+ File.separator + "picture" + File.separator + "system2.jpg";          Icon icon = new ImageIcon(picPath);         jlb_up.setIcon(icon); // NOI18N                           jlb_up.setText("南邮自行车管理系统");         jlb_up.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);         javax.swing.GroupLayout jp_upLayout = new javax.swing.GroupLayout(jp_up);         jp_up.setLayout(jp_upLayout);         jp_upLayout.setHorizontalGroup(             jp_upLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)             .addComponent(jlb_up, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)         );         jp_upLayout.setVerticalGroup(             jp_upLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)             .addComponent(jlb_up, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)         );         jsp1.setBackground(new java.awt.Color(204, 204, 255));         jsp1.setDividerLocation(150);         jp_left.setBackground(new java.awt.Color(204, 204, 255));         jspz.setBackground(new java.awt.Color(204, 204, 255));         javax.swing.GroupLayout jp_leftLayout = new javax.swing.GroupLayout(jp_left);         jp_left.setLayout(jp_leftLayout);         jp_leftLayout.setHorizontalGroup(             jp_leftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)             .addComponent(jspz, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)         );         jp_leftLayout.setVerticalGroup(             jp_leftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)             .addComponent(jspz, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)         );         jsp1.setLeftComponent(jp_left);         jpy.setBackground(new java.awt.Color(204, 204, 255));         javax.swing.GroupLayout jpyLayout = new javax.swing.GroupLayout(jpy);         jpy.setLayout(jpyLayout);         jpyLayout.setHorizontalGroup(             jpyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)             .addGap(0, 581, Short.MAX_VALUE)         );         jpyLayout.setVerticalGroup(             jpyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)             .addGap(0, 460, Short.MAX_VALUE)         );         jsp1.setRightComponent(jpy);         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());         getContentPane().setLayout(layout);         layout.setHorizontalGroup(             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)             .addComponent(jp_up, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)             .addComponent(jsp1, javax.swing.GroupLayout.DEFAULT_SIZE, 900, Short.MAX_VALUE)         );         layout.setVerticalGroup(             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)             .addGroup(layout.createSequentialGroup()                 .addComponent(jp_up, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)                 .addComponent(jsp1, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE))         );         pack();     }// </editor-fold>               //2.6.3     public void addListener(){         jt.addMouseListener(                 new MouseAdapter(){                     public void mouseClicked(MouseEvent e){                                                                    //实现mouseClicked方法                         DefaultMutableTreeNode dmtntemp =  (DefaultMutableTreeNode)jt.getLastSelectedPathComponent();        //得到当前选中节点对象                         MyNode mynode = (MyNode)dmtntemp.getUserObject();                                                  //得到自定义节点对象                         String id = mynode.getid();                                                                         //得到选中节点的id                                                  //根据id值显示不同的卡片                         if(id.equals("0")){System.out.println("欢迎页面");}                                                  else if (id.equals("11")){System.out.println("进入我的资产界面");                          jpy.add(myequipment, "myequipment");                                                                //将searchequipment对象添加到jpy画板                          cl.show(jpy, "myequipment");                                                                       //将searchequipment对象添加到卡片                          myequipment.setFocusable(true);                         }                         else if (id.equals("12")){System.out.println("进入设备预定界面");                         jpy.add(equipmentordered, "equipmentordered");                                                      //将searchequipment对象添加到jpy画板                          cl.show(jpy, "equipmentordered");                                                                  //将searchequipment对象添加到卡片                          equipmentordered.setFocusable(true);                         }                         else if (id.equals("13")){ System.out.println("进入设备退还界面"); }                                                                                else if (id.equals("14")){System.out.println("维修反馈");                         jpy.add(equipmentrequiremended, "equipmentrequiremended");                                            //将searchequipment对象添加到jpy画板                         cl.show(jpy, "equipmentrequiremended");                                                             //将searchequipment对象添加到卡片                         equipmentrequiremended.setFocusable(true);                         }                                                    else if (id.equals("21")){System.out.println("用户操作");}                         else if (id.equals("22")){System.out.println("用户反馈");                         }                         else if (id.equals("22")){System.out.println("用户提醒");                         }                                                                                                    else if (id.equals("31")){System.out.println("密码修改页面");                         jpy.add(userpwdmodify, "userpwdmodify");                                                            //将searchequipment对象添加到jpy画板                         cl.show(jpy, "userpwdmodify");                                                                      //将searchequipment对象添加到卡片                         userpwdmodify.setFocusable(true);                         }                         else if (id.equals("32")){System.out.println("基本信息查询页面");}                         else if (id.equals("33")){System.out.println("退出");                         int i = JOptionPane.showConfirmDialog(jpy, "您确定要退出系统吗?","询问",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);                         if(i==0){System.exit(0);}                         }                     }                 });         jt.setToggleClickCount(1);//将展开节点的鼠标单击次数设置为1     }              //     public static void main(String args[]){//         SuperUserClient s = new SuperUserClient("1221101");//         System.out.println("**"+s.getUserId());//     }                    }

 

 

shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

private String getMac() {                String macSerial = null;                String str = "";                try {                        Process pp = Runtime.getRuntime().exec(                                        "cat /sys/class/net/wlan0/address ");                        InputStreamReader ir = new InputStreamReader(pp.getInputStream());                        LineNumberReader input = new LineNumberReader(ir);                        for (; null != str;) {                                str = input.readLine();                                if (str != null) {                                        macSerial = str.trim();// 去空格                                        break;                                }                        }                } catch (IOException ex) {                        // 赋予默认值                        ex.printStackTrace();                }                return macSerial;        }


shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

package test.img;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.net.URL;import java.util.regex.Matcher;import java.util.regex.Pattern;public class DownLoad {        /**         * 1.获得网页html代码         */        public String getHtmlCode(String httpUrl) throws IOException {                String content = "";                URL url = new URL(httpUrl); // 创建URL类对象                BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); // //使用openStream得到一输入流并由此构造一个BufferedReader对象                String line;                while ((line = br.readLine()) != null) { // 建立读取循环,并判断是否有读取值                        content += line;                }                br.close();                return content;        }        /**         * 2.下载网页代码及图片并替换图片链接地址         */        public void downImg(String url) throws IOException {                String searchImgReg = "(?x)(src|SRC|background|BACKGROUND)=('|\")(http://.*?/)(.*?.(jpg|JPG|png|PNG|gif|GIF))('|\")";                String content = this.getHtmlCode(url);                System.out.println(content);                // 下载图片                Pattern pattern = Pattern.compile(searchImgReg);                Matcher matcher = pattern.matcher(content);                while (matcher.find()) {                        this.getHtmlPicture(matcher.group(3), matcher.group(4));                }        }        /**         * 3.下载网页上图片         */        public void getHtmlPicture(String httpUrl, String imgPath) {                URL url;                BufferedInputStream bi;                FileOutputStream fo;                try {                        String fileName = imgPath.substring(imgPath.lastIndexOf("/"));                        String filePath = "c://pic/";                        url = new URL(httpUrl + imgPath);                        // 如果该目录不存在,则创建之                        File uploadFilePath = new File(filePath);                        if (uploadFilePath.exists() == false) {                                uploadFilePath.mkdirs();                        }                        bi = new BufferedInputStream(url.openStream());                        fo = new FileOutputStream(new File(filePath + fileName));                        int length;                        while ((length = bi.read()) != -1) {                                fo.write(length);                        }                        fo.flush();                        fo.close();                        bi.close();                } catch (Exception e) {                        e.printStackTrace();                }        }        /**         * 测试方法         */        public static void main(String[] args) throws IOException {                String url = "http://www.taobao.com";                DownLoad dl = new DownLoad();                dl.downImg(url);        }}


shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

import java.awt.AWTException;import java.awt.MenuItem;import java.awt.PopupMenu;import java.awt.SystemTray;import java.awt.TrayIcon;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.WindowEvent;import java.awt.event.WindowStateListener;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.Timer;import javax.swing.UIManager;/** * * @author Mr.LiuTao */public class TrayByJdk extends JFrame implements ActionListener{        private JPanel pane = null;    private JButton button = null; // 启动托盘图标的按钮    private JLabel label = null; // 用来显示系统是否支持托盘的信息    private TrayIcon trayIcon = null; // 托盘图标    private Timer shanshuo = null;    private ImageIcon icon1 = null;    private ImageIcon icon2 = null;    private SystemTray tray = null; // 本操作系统托盘的实例    boolean gengai = false;    //采用jdk1.6的托盘技术 实现跨平台的应用    public TrayByJdk() {        //super("托盘技术演示");        icon1 = new ImageIcon("G:\\javaworks\\eclipsework\\山寨QQClient\\images\\16.gif"); // 将要显示到托盘中的图标        icon2 = new ImageIcon("G:\\javaworks\\eclipsework\\山寨QQClient\\images\\15.gif"); // 将要显示到托盘中的图标        try {            // 将LookAndFeel设置成Windows样式            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");        } catch (Exception ex) {            ex.printStackTrace();        }        pane = new JPanel();        button = new JButton("缩小到托盘");        button.setEnabled(false);        label = new JLabel("本操作系统不支持托盘");        pane.add(label);        pane.add(button);        //判断是否支持托盘        if (SystemTray.isSupported()) {            this.tray();        }        shanshuo = new Timer(1000,this);        shanshuo.start();        this.getContentPane().add(pane);        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        this.setSize(300, 200);        this.addWindowStateListener(new WindowStateListener () {            public void windowStateChanged(WindowEvent state) {                if(state.getNewState() == 1 || state.getNewState() == 7) {                    yinca();                }            }        });                this.setVisible(false);        System.out.println("=============="+this.isVisible());    }    /**     * 托盘相关代码     */    private void tray() {        label.setText("本操作系统支持托盘");        button.setEnabled(true);        tray = SystemTray.getSystemTray(); // 获得本操作系统托盘的实例        //ImageIcon icon = new ImageIcon("tray.gif"); // 将要显示到托盘中的图标                PopupMenu pop = new PopupMenu(); // 构造一个右键弹出式菜单        MenuItem show = new MenuItem("显示窗口");        MenuItem exit = new MenuItem("退出演示");        MenuItem author = new MenuItem("Author");                        /**         * TrayIcon有三个构造         * TrayIcon(Image image) 用“图标”来构造         * TrayIcon(Image image, String tooltip) 用“图标”和“ToolTip”构造         * TrayIcon(Image image, String tooltip, PopupMenu popup) 用“图标”,“ToolTip”,“弹出菜单”来构造一个托盘图标         */        trayIcon = new TrayIcon(icon1.getImage(), "托盘技术演示", pop);        // 点击本按钮后窗口被关闭,托盘图标被添加到系统的托盘中        button.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent e) {                                try {                    tray.add(trayIcon); // 将托盘图标添加到系统的托盘实例中                    setVisible(false); // 使窗口不可视                } catch (AWTException ex) {                    ex.printStackTrace();                }            }        });        /**         * 添加鼠标监听器,当鼠标在托盘图标上双击时,默认显示窗口         */        trayIcon.addMouseListener(new MouseAdapter() {            public void mouseClicked(MouseEvent e) {                if (e.getClickCount() == 2) { // 鼠标双击                    tray.remove(trayIcon); // 从系统的托盘实例中移除托盘图标                    setVisible(true); // 显示窗口                }            }        });        show.addActionListener(new ActionListener() { // 点击“显示窗口”菜单后将窗口显示出来            public void actionPerformed(ActionEvent e) {                tray.remove(trayIcon); // 从系统的托盘实例中移除托盘图标                setVisible(true); // 显示窗口            }        });        exit.addActionListener(new ActionListener() { // 点击“退出演示”菜单后推出程序            public void actionPerformed(ActionEvent e) {                System.exit(0); // 退出程序            }        });        author.addActionListener(new ActionListener() { // 点击“退出演示”菜单后推出程序            public void actionPerformed(ActionEvent e) {                showMessage();            }        });        pop.add(show);        pop.add(exit);        pop.add(author);    }    /**     * 显示信息     */    private void showMessage() {        JOptionPane.showMessageDialog(this, new JLabel("这是一个系统托盘"), "消息", JOptionPane.INFORMATION_MESSAGE);    }    public static void main(String[] args) {        new TrayByJdk().yinca();    }                public void yinca(){         try {            tray.add(trayIcon);        } catch (AWTException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } // 将托盘图标添加到系统的托盘实例中         setVisible(false); // 使窗口不可视    }    @Override    public void actionPerformed(ActionEvent arg0) {        if(!gengai){            trayIcon.setImage(icon2.getImage());            gengai = true;        }else{            trayIcon.setImage(icon1.getImage());            gengai = false;        }    }        }


shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

        IField field;        String typeSignature = field.getTypeSignature();        typeSignature = JavaModelUtil.getResolvedTypeName(typeSignature,                field.getDeclaringType());        field.getJavaProject().findType(typeSignature);


shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

import java.awt.event.WindowEvent;import java.awt.event.WindowStateListener;import javax.swing.JFrame;public class WinFrame extends JFrame {    public WinFrame(){        this.setName("Window 窗口状态");        this.setSize(300,300);        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        this.addWindowStateListener(new WindowStateListener () {            public void windowStateChanged(WindowEvent state) {                                if(state.getNewState() == 1 || state.getNewState() == 7) {                    System.out.println("窗口最小化");                }else if(state.getNewState() == 0) {                    System.out.println("窗口恢复到初始状态");                }else if(state.getNewState() == 6) {                    System.out.println("窗口最大化");                }            }        });        this.setVisible(true);    }    public static void main(String[] args) {        new WinFrame();    }}


shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

import java.io.BufferedReader;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.URI;import java.net.URISyntaxException;import java.util.ArrayList;import java.util.List;import java.util.regex.Matcher;import java.util.regex.Pattern;import org.apache.commons.codec.binary.StringUtils;import org.apache.commons.httpclient.HttpStatus;import org.apache.commons.io.IOUtils;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.ParseException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import java.io.File;  import java.io.IOException; import java.sql.Timestamp; import java.lang.*;import org.jsoup.Jsoup;  import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;import java.awt.*;import javax.swing.JFrame;public class CatchTestApp {    private final static HttpClient httpClient = new DefaultHttpClient();    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub            try{            System.out.println("输入你的要抓取的网页名称:");            BufferedReader in = new BufferedReader(new  InputStreamReader(System.in));                String s = in.readLine();            String keyWord = s;                String url = LocateURL(keyWord);            String charset = LocateCharSet(url);            System.out.println("显示抓取到的页面编码方式:"+charset);            CatchWeb(url,keyWord,charset);        }catch(IOException e){            e.printStackTrace();        }    }        //定位百度搜索到的第一条网站URL方法    public static String LocateURL(String keyword){                //设置百度查询的结果        String threadUrl ="http://www.baidu.com/s?wd="+keyword;        try{        Document doc = (Document)Jsoup.connect(threadUrl).get(); //用Document记录页面信息        //System.out.println(doc);        //定位到一条网站URL         for(Element ele : doc.getElementById("1").select("tbody > tr")){                if(!ele.select("td").toString().equals("")){                      String url = ele.select("td").get(0).select("a").attr("href");                       System.out.println("显示抓取到的页面URL:"+url);                     threadUrl = url;                }           }                }catch(IOException e){            e.printStackTrace();        }        return threadUrl;    }            //获取所要抓取网页的编码方式     public static String LocateCharSet(String url){                String sub = "utf-8";          String s = "";          String t="text";          try{          Document doc = Jsoup.connect(url).get();                        //判断编码方式          Elements eles = doc.getElementsByTag("head").select("meta[http-equiv]");          for(Element ele :eles){              if(ele.attr("http-equiv").equals("Content-Type")||                      ele.attr("http-equiv").equals("Content-type")||                      ele.attr("http-equiv").equals("content-type")||                      ele.attr("http-equiv").equals("content-Type")){                  String[] str = ele.attr("content").split("[=]");                  sub = str[1];                }                        }                    //判断编码方式所在    (不要用这个方法,不好) //          for(int i=0 ; s.equals(t)!= true ; i++){         //                  String charSet = doc.getElementsByTag("head").select("meta[http-equiv]").get(i).attr("content");      //                  s=charSet.substring(0,t.length());//                  String[] str = charSet.split("[=]"); //                  sub = str[1]; //          }                }catch(IOException e){           e.printStackTrace();          }            return sub;          }            private static Document parseJSoupDocumentFromHtml(String url) {        // TODO Auto-generated method stub        return null;    }    //抓取网页全部内容方法    @SuppressWarnings("deprecation")    public static void CatchWeb(String url,String keyword,String charset){                try{            HttpGet httpget = new HttpGet(url);// Get请求             HttpResponse httpresponse = httpClient.execute(httpget); // 发送请求             HttpEntity entity = httpresponse.getEntity();// 获取返回数据                String chars = EntityUtils.getContentCharSet(entity);            System.out.println("charset:"+charset);            if(chars != null){                charset = chars;            }            System.out.println("chars:"+chars);            String info =EntityUtils.toString(entity, charset);            System.out.println("显示响应信息状态:"+httpresponse.getStatusLine());            System.out.println(info);            File(info,keyword,charset);                }catch(ParseException e){            e.printStackTrace();        }catch(IOException e){            e.printStackTrace();        }            }        //将抓取的页面信息输出到txt文档    public static void File(String info,String keyword,String charset){        File file = new File("D:/抓获网页源码库/"+keyword+"网页源码.txt");            try{                FileOutputStream out = new FileOutputStream(file);                byte b[]= info.getBytes(charset);                System.out.println("数据正在写入文本文档中......");                out.write(b);                out.close();                System.out.println("数据保存成功!");            }catch(Exception e){                e.printStackTrace();            }                }    }


shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

public class Telnet {    public static void main(String args[]) {        String[] keys = allkeys("localhost", 11211).split("\n");        Arrays.sort(keys);        for(String s : keys){            System.out.println(s);        }        System.out.println(telnet("localhost", 11211, "stats"));    }    public static String allkeys(String host, int port){        StringBuffer r = new StringBuffer();        try {            Socket socket = new Socket(host, port);            PrintWriter os = new PrintWriter(socket.getOutputStream());            BufferedReader is = new BufferedReader(new InputStreamReader( socket.getInputStream()));            os.println("stats items");            os.flush();            String l ;            while (!(l = is.readLine()).equals("END")) {                r.append(l).append("\n");            }            String rr = r.toString();            Set<String> ids = new HashSet<String>();            if(rr.length() > 0){                r = new StringBuffer();//items                 rr.replace("STAT items", "");                for(String s : rr.split("\n")){                    ids.add(s.split(":")[1]);                }                if (ids.size() > 0){                    r = new StringBuffer();//                    for(String s : ids){                        os.println("stats cachedump "+ s +" 0");                        os.flush();                        while (!(l = is.readLine()).equals("END")) {                            r.append(l.split(" ")[1]).append("\n");                        }                    }                }            }                        os.close();            is.close();            socket.close();        } catch (Exception e) {            System.out.println("Error" + e);        }        return r.toString();    }    public static String telnet(String host, int port, String cmd){        StringBuffer r = new StringBuffer();        try {            Socket socket = new Socket(host, port);            PrintWriter os = new PrintWriter(socket.getOutputStream());            BufferedReader is = new BufferedReader(new InputStreamReader( socket.getInputStream()));            os.println(cmd);            os.flush();            String l ;            while (!(l = is.readLine()).equals("END")) {                r.append(l).append("\n");            }            os.close();            is.close();            socket.close();        } catch (Exception e) {            System.out.println("Error" + e);        }        return r.toString();    }    }


shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()

public String getStandardTime(long timestamp) {                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss" , Locale.getDefault());                sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));                Date date = new Date(timestamp * 1000);                sdf.format(date);                return sdf.format(date);        }


shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()