`
53873039oycg
  • 浏览: 825665 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
获取客户端IP java 获取客户端IP地址
/**
     * 获取客户端IP地址
     * */
    public String getRemortIP(HttpServletRequest request) {   
        String ip = request.getHeader("x-forwarded-for");   
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
            ip = request.getHeader("Proxy-Client-IP");   
        }   
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
            ip = request.getHeader("WL-Proxy-Client-IP");   
        }   
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
            ip = request.getRemoteAddr();   
        }   
        return ip;   
    }
查找最小K个数 算法 查找最小的K个数
package com.chinahrt.zyn.pango;

import java.util.ArrayList;
import java.util.List;

public class FindMinKFromN {

	
	/**
	 * 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

	输入:
	每个测试案例包括2行:
	第一行为2个整数n,k(1<=n,k<=200000),表示数组的长度。
	第二行包含n个整数,表示这n个数,数组中的数的范围是[0,1000 000 000]。
	输出:
	对应每个测试案例,输出最小的k个数,并按从小到大顺序打印。

	样例输入:
	8 4 4 5 1 6 2 7 3 8
	样例输出:
	1 2 3 4
	 */
	public List<Integer> getMinList(Integer[] num,int k){
		List<Integer> list = new ArrayList<Integer> ();
		for(Integer i:num){
			list = addInteger(list,i,0,list.size()==0?0:list.size()-1,k);
		}
		return list;
	}
	
	public List<Integer> addInteger(List<Integer> list ,int a,int startIndex,int endIndex,int length){
		if(list.size()==0){
			list.add(a);
			return list;
		}
		//如果小于最小的插入前面
		if(a<=list.get(startIndex)){
			list.add(startIndex,a);
			if(list.size()>length){
				list.remove(list.size()-1);
			}
			return list;
		}
		//如果大于最大的插入后面
		if(a >= list.get(endIndex)){
			list.add((endIndex+1),a);
			if(list.size()>length){
				list.remove(list.size()-1);
			}
			return list;
		}
		//如果位于两者之间,插入
		if(list.get(startIndex)<a &&((endIndex -startIndex)==1) && list.get(endIndex)>a){
			list.add((startIndex+1),a);
			if(list.size()>length){
				list.remove(list.size()-1);
			}
			return list;
		}
		//如果以上都不执行,二分查找比较插入
		int middle;
		if((endIndex - startIndex)%2!=0){
			middle = (endIndex - startIndex+1)/2;
		}else{
			middle = (endIndex - startIndex)/2;
		}
		if(a>list.get(middle)){
			return addInteger(list,a,middle,endIndex,length);
		}else{
			return addInteger(list,a,startIndex,middle,length);
		}
	}
	
	
	/**
	 * @param args
	 * Administrator
	 * 2013-4-13 上午10:26:50
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FindMinKFromN f = new FindMinKFromN();
		Integer[] a = {4,5,1,6,2,7,3,8};
		List<Integer> list = f.getMinList(a, 4);
		for(Integer b:list){
			System.out.println(b);
		}
		
	}

}
ftp操作 java Java Ftp Client
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.TimeZone;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import org.apache.log4j.Logger;

public class FtpClient {
	private FTPClient ftpClient;
	private String strIp;
	private int intPort;
	private String user;
	private String password;

	private static Logger logger = Logger.getLogger(FtpClient.class.getName());

	/* *
	 * Ftp构造函数
	 */
	public FtpClient(String strIp, int intPort, String user, String Password) {
		this.strIp = strIp;
		this.intPort = intPort;
		this.user = user;
		this.password = Password;
		this.ftpClient = new FTPClient();
	}

	/**
	 * @return 判断是否登入成功
	 * */
	public boolean ftpLogin() {
		boolean isLogin = false;
		FTPClientConfig ftpClientConfig = new FTPClientConfig();
		ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
		this.ftpClient.setControlEncoding("GBK");
		this.ftpClient.configure(ftpClientConfig);
		try {
			if (this.intPort > 0) {
				this.ftpClient.connect(this.strIp, this.intPort);
			} else {
				this.ftpClient.connect(this.strIp);
			}
			// FTP服务器连接回答
			int reply = this.ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				this.ftpClient.disconnect();
				logger.error("登录FTP服务失败!");
				return isLogin;
			}
			this.ftpClient.login(this.user, this.password);
			// 设置传输协议
			this.ftpClient.enterLocalPassiveMode();
			this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			logger.info("恭喜" + this.user + "成功登陆FTP服务器");
			isLogin = true;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(this.user + "登录FTP服务失败!" + e.getMessage());
		}
		this.ftpClient.setBufferSize(1024 * 2);
		this.ftpClient.setDataTimeout(30 * 1000);
		return isLogin;
	}

	/**
	 * @退出关闭服务器链接
	 * */
	public void ftpLogOut() {
		if (null != this.ftpClient && this.ftpClient.isConnected()) {
			try {
				boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
				if (reuslt) {
					logger.info("成功退出服务器");
				}
			} catch (IOException e) {
				e.printStackTrace();
				logger.warn("退出FTP服务器异常!" + e.getMessage());
			} finally {
				try {
					this.ftpClient.disconnect();// 关闭FTP服务器的连接
				} catch (IOException e) {
					e.printStackTrace();
					logger.warn("关闭FTP服务器的连接异常!");
				}
			}
		}
	}

	/***
	 * 上传Ftp文件
	 * 
	 * @param localFile
	 *            当地文件
	 * @param romotUpLoadePath上传服务器路径
	 *            - 应该以/结束
	 * */
	public boolean uploadFile(File localFile, String romotUpLoadePath) {
		BufferedInputStream inStream = null;
		boolean success = false;
		try {
			this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
			inStream = new BufferedInputStream(new FileInputStream(localFile));
			logger.info(localFile.getName() + "开始上传.....");
			success = this.ftpClient.storeFile(localFile.getName(), inStream);
			if (success == true) {
				logger.info(localFile.getName() + "上传成功");
				return success;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			logger.error(localFile + "未找到");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return success;
	}

	/***
	 * 下载文件
	 * 
	 * @param remoteFileName
	 *            待下载文件名称
	 * @param localDires
	 *            下载到当地那个路径下
	 * @param remoteDownLoadPath
	 *            remoteFileName所在的路径
	 * */

	public boolean downloadFile(String remoteFileName, String localDires,
			String remoteDownLoadPath) {
		String strFilePath = localDires + remoteFileName;
		BufferedOutputStream outStream = null;
		boolean success = false;
		try {
			this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
			outStream = new BufferedOutputStream(new FileOutputStream(
					strFilePath));
			logger.info(remoteFileName + "开始下载....");
			success = this.ftpClient.retrieveFile(remoteFileName, outStream);
			if (success == true) {
				logger.info(remoteFileName + "成功下载到" + strFilePath);
				return success;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(remoteFileName + "下载失败");
		} finally {
			if (null != outStream) {
				try {
					outStream.flush();
					outStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		if (success == false) {
			logger.error(remoteFileName + "下载失败!!!");
		}
		return success;
	}

	/***
	 * @上传文件夹
	 * @param localDirectory
	 *            当地文件夹
	 * @param remoteDirectoryPath
	 *            Ftp 服务器路径 以目录"/"结束
	 * */
	public boolean uploadDirectory(String localDirectory,
			String remoteDirectoryPath) {
		File src = new File(localDirectory);
		try {
			remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
			this.ftpClient.makeDirectory(remoteDirectoryPath);
			// ftpClient.listDirectories();
		} catch (IOException e) {
			e.printStackTrace();
			logger.info(remoteDirectoryPath + "目录创建失败");
		}
		File[] allFile = src.listFiles();
		for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
			if (!allFile[currentFile].isDirectory()) {
				String srcName = allFile[currentFile].getPath().toString();
				uploadFile(new File(srcName), remoteDirectoryPath);
			}
		}
		for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
			if (allFile[currentFile].isDirectory()) {
				// 递归
				uploadDirectory(allFile[currentFile].getPath().toString(),
						remoteDirectoryPath);
			}
		}
		return true;
	}

	/***
	 * @下载文件夹
	 * @param localDirectoryPath本地地址
	 * @param remoteDirectory
	 *            远程文件夹
	 * */
	public boolean downLoadDirectory(String localDirectoryPath,
			String remoteDirectory) {
		try {
			String fileName = new File(remoteDirectory).getName();
			localDirectoryPath = localDirectoryPath + fileName + "//";
			new File(localDirectoryPath).mkdirs();
			FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
			for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
				if (!allFile[currentFile].isDirectory()) {
					downloadFile(allFile[currentFile].getName(),
							localDirectoryPath, remoteDirectory);
				}
			}
			for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
				if (allFile[currentFile].isDirectory()) {
					String strremoteDirectoryPath = remoteDirectory + "/"
							+ allFile[currentFile].getName();
					downLoadDirectory(localDirectoryPath,
							strremoteDirectoryPath);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			logger.info("下载文件夹失败");
			return false;
		}
		return true;
	}

	// FtpClient的Set 和 Get 函数
	public FTPClient getFtpClient() {
		return ftpClient;
	}

	public void setFtpClient(FTPClient ftpClient) {
		this.ftpClient = ftpClient;
	}

	public static void main(String[] args) throws IOException {
		FtpClient ftp = new FtpClient("192.168.1.111", 21, "test", "123456");
		ftp.ftpLogin();
		// 上传文件夹
		ftp.uploadDirectory("D:\\test\\2013", "/2013");
		// 下载文件夹
		// ftp.downLoadDirectory("d://tmp//", "/home/data/DataProtemp");
		ftp.ftpLogOut();
	}
}
sqlserver2005分页 sql mysql sqlserver oracel分页sql语句
  select * from (select row_number() over by(id)   
 rownum t.* from (select * from product) t where rownum <= pageNow * pageSize)where rownum > (pagenow - 1)* pageSize)
jmagic处理图片 基数排序, java JMagick处理图片代码收集
package org.wsr.util;

import java.awt.Dimension;  
import java.awt.Point;  
import java.awt.Rectangle;  
import java.io.File;  
  
import magick.CompositeOperator;  
import magick.CompressionType;  
import magick.DrawInfo;  
import magick.ImageInfo;  
import magick.MagickException;  
import magick.MagickImage;  
import magick.PixelPacket;  
import magick.PreviewType;  
  
public class JMagicjWrapper {  
	
public static void main(String[] args) throws MagickException{  
        
        //test for function imageResize   
          
//        JMagicjWrapper.imageResize("pics.jpg", "reSize20x30.png", 20, 30);  
//        JMagicjWrapper.imageResize("pics.jpg", "reSize250x200.jpeg", 250, 200);  
//        JMagicjWrapper.imageResize("pics.jpg", "reSize50x50.jpg", 50, 50);  
//        JMagicjWrapper.imageResize("pics.jpg", "reSize120x120.bmp", 120, 120);  
//        JMagicjWrapper.imageResize("pics.jpg", "reSize.tif", 20, 30);//not create file   
//          
          
        //test for function createWaterPrintByImg   
        JMagicjWrapper.createWaterPrintByImg("f://1.jpg", "f://4.jpg", "f://watermark.gif", new Point(0,0));  
        //JMagicjWrapper.imageResize("wpl.gif", "logo250x200.gif", 250, 200);  
        //Because file "wpl.gif" may not be release, the later function cause a error, can not open file handle.   
        //JMagicjWrapper.createWaterPrintByImg("pics.jpg", "wpl.gif", "logoFull.jpg", new Point(1680,1050));//not create file   
        //JMagicjWrapper.createWaterPrintByImg("pics.jpg", "wpl.gif", "logoExt.jpg", new Point(2000,1000));//not create file   
          
        //test for function createWaterPrintByText   
        //This function can not handle Chinese Character, I'll continue to takle the issue    
        //JMagicjWrapper.createWaterPrintByText("pics1.jpg", "wpt.gif", "For Test", new Point(300,300), 100);  
    }  
  
    private static final String[] Type = {  
        ".JPG",  
        ".JPEG",  
        ".BMP",  
        ".GIF",  
        ".PNG"  
    };  
      
    public static boolean checkType(String path){  
        for (int i = 0; i < Type.length; i++) {  
            if (path.toUpperCase().endsWith(Type[i])) {  
                return true;  
            }else {  
                continue;  
            }  
        }  
        return false;  
    }  
      
    /**改变图片大小 
     * @param   filePath    原图片位置 
     *          toPath      新图片位置 
     *          width       新图片的宽度 
     *          height      新图片的高度 
     * @return  
     * @throw 
     * @author sulliy@sina.com 2010-8-11 
     */  
    public static void imageResize(String filePath, String toPath, int width, int height)  
            throws MagickException {  
        ImageInfo info = null;  
        MagickImage image = null;  
        Dimension imageDim = null;  
        MagickImage scaled = null;  
          
        if (!checkType(filePath) || !checkType(toPath)) {  
            return;  
        }  
          
        try {  
            info = new ImageInfo();
            image = new MagickImage(info);  
            imageDim = image.getDimension();  
            if (width <= 0 || height <= 0) {  
                height = 120;  
                width = 120;  
            }  
            scaled = image.scaleImage(width, height);  
            scaled.setFileName(toPath);  
            scaled.writeImage(info);  
        } finally {  
            if (scaled != null) {  
                scaled.destroyImages();  
            }  
        }  
    }  
  
    /**创建图片水印 
     * @param       filePath    源文件路径 
     *              toImg       生成文件位置 
     *              logoPath    logo路径 
     *              pos         logo在源图片中的相对位置,以像素点为单位 
     * @return  
     * @throw   MagickException 
     * @author sulliy@sina.com 2010-8-11 
     */  
    public static void createWaterPrintByImg(String filePath, String toImg,  
            String logoPath, Point pos) throws MagickException {  
        if (!checkType(filePath) || !checkType(toImg) || !checkType(logoPath)) {  
            return;  
        }
          
       ImageInfo info = new ImageInfo();  
        MagickImage fImage = null;  
        MagickImage sImage = null;  
        MagickImage fLogo = null;  
        MagickImage sLogo = null;  
        Dimension imageDim = null;
        Dimension logoDim = null;
        try {
        	//原来图片
            fImage = new MagickImage(new ImageInfo(filePath));
            imageDim = fImage.getDimension();
            int width = imageDim.width;
            int height = imageDim.height;
            sImage = fImage.scaleImage(width, height);
              
            fLogo = new MagickImage(new ImageInfo(logoPath));
            logoDim = fLogo.getDimension();
            int lw = logoDim.width;
            int lh = logoDim.height;
            sLogo = fLogo.scaleImage(lw, lh);
              
            //开始打水印,从左上角开始;如果到右边界则重新开始一行的打印(x=0,y=y+h)
            int startX = 0;
            int startY = 0;
            do {            	
                sImage.compositeImage(CompositeOperator.AtopCompositeOp, sLogo,  
                        startX, startY);
                startX += (logoDim.width + 60);
            	if (startX >= width){
            		startY += logoDim.height * 2;
            		startX = 0;
            	}
    		} while(startY <= height);
            
            sImage.setFileName(toImg);
            sImage.writeImage(info);
        } finally {
            if (fImage != null) {
                fImage.destroyImages();
            }
            if (sImage != null) {
            	sImage.destroyImages();
            }
            if (fLogo != null) {
            	fLogo.destroyImages();
            }
            if (sLogo != null) {
            	sLogo.destroyImages();
            }
        }
    }
  
    /**创建文字水印 
     * @param       filePath    源文件路径 
     *              toImg       生成文件位置 
     *              text        水印文本 
     *              pos         logo在源图片中的相对位置,以像素点为单位 
     *              pointSize   用于设置点阵大小 
     * @return  
     * @throw   MagickException 
     * @author sulliy@sina.com 2010-8-11 
     */  
    public static void createWaterPrintByText(String filePath, String toImg, String text  
            , Point pos, int pointSize)  
            throws MagickException {  
        if (!checkType(filePath) || !checkType(toImg)) {  
            return;  
        }  
          
        if (null == text || "".equals(text)) {  
            text = "sulliy@sina.com";  
        }  
          
        ImageInfo info = new ImageInfo(filePath);  
        if (filePath.toUpperCase().endsWith("JPG")  
                || filePath.toUpperCase().endsWith("JPEG")) {  
            info.setCompression(CompressionType.JPEGCompression); // 压缩类别为JPEG格式   
            info.setPreviewType(PreviewType.JPEGPreview); // 预览格式为JPEG格式   
            info.setQuality(95);  
        }  
        MagickImage aImage = new MagickImage(info);  
        Dimension imageDim = aImage.getDimension();  
        int width = imageDim.width;  
        int height = imageDim.height;  
          
        if (width <= (int)pos.getX() || height <= (int)pos.getY()) {  
            pos.setLocation(0, 0);  
        }  
          
        int a = 0;  
        int b = 0;  
        String[] as = text.split("");  
        for (String string : as) {  
            if (string.matches("[/u4E00-/u9FA5]")) {  
                a++;  
            }  
            if (string.matches("[a-zA-Z0-9]")) {  
                b++;  
            }  
        }  
        int tl = a * 12 + b * 6 ;//字符长度   
        MagickImage scaled = aImage.scaleImage(width, height);  
        if (width > tl && height > 5) {  
            DrawInfo aInfo = new DrawInfo(info);  
            aInfo.setFill(PixelPacket.queryColorDatabase("white"));  
            aInfo.setUnderColor(new PixelPacket(65535, 65535, 65535, 65535));//设置为透明颜色   
            aInfo.setPointsize(pointSize);  
            // 解决中文乱码问题,自己可以去随意定义个自己喜欢字体,我在这用的微软雅黑   
            String fontPath = "C:/WINDOWS/Fonts/MSIMHEI.TTF";  
            // String fontPath = "/usr/maindata/MSYH.TTF";   
            aInfo.setFont(fontPath);  
            aInfo.setTextAntialias(true);  
            aInfo.setOpacity(0);//透明度   
            aInfo.setText(text);  
            aInfo.setGeometry("+" + ((int)pos.getX() + "+" + (int)pos.getY()));  
            scaled.annotateImage(aInfo);  
        }  
        scaled.setFileName(toImg);  
        scaled.writeImage(info);  
        scaled.destroyImages();  
    }  
  
    /**切取图片 
     * @param       imgPath     原图路径 
     *              toPath      生成文件位置 
     *              w           左上位置横坐标 
     *              h           左上位置竖坐标 
     *              x           右下位置横坐标 
     *              y           右下位置竖坐标 
     * @return  
     * @throw   MagickException 
     * @author sulliy@sina.com 2010-8-11 
     */  
    public static void cutImg(String imgPath, String toPath, int w, int h,  
            int x, int y) throws MagickException {  
        ImageInfo infoS = null;  
        MagickImage image = null;  
        MagickImage cropped = null;  
        Rectangle rect = null;  
        try {  
            infoS = new ImageInfo(imgPath);  
            image = new MagickImage(infoS);  
            rect = new Rectangle(x, y, w, h);  
            cropped = image.cropImage(rect);  
            cropped.setFileName(toPath);  
            cropped.writeImage(infoS);  
  
        } finally {  
            if (cropped != null) {  
                cropped.destroyImages();  
            }  
        }  
    }  
      
    /**删除图片文件 
     * @param   src     图片位置 
     * @return  
     * @throw 
     * @author sulliy@sina.com 2010-8-11 
     */  
    public static boolean removeFile(String src) throws SecurityException{  
        try {  
            if (!checkType(src)) {  
                return false;  
            }  
              
            File file = new File(src);  
            return file.delete();         
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }
    
}  
java cmd java java 与cmd 命令窗口交互操作
package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Test1 {

	public static void main(String[] args) {  
		  
        try {  
            Process process = Runtime.getRuntime().exec("cmd");  //cmd /c start 可以打开另一个窗口
            PrintWriter writer = new PrintWriter(process.getOutputStream());  
            new CommandThread(writer).start();  
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));  
              
            String s = null;  
            while ((s = br.readLine()) != null) {  
                System.out.println(s);  
            }  
            Thread.currentThread().interrupt();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
    }  
      
    static class CommandThread extends Thread{  
        PrintWriter writer;  
        BufferedReader br = null;  
        CommandThread(PrintWriter writer){  
            this.writer = writer;  
            br = new BufferedReader(new InputStreamReader(System.in));  
            this.setDaemon(true);  
        }  
          
        @Override  
        public void run() {  
            try {  
                String cmd = null;  
                while((cmd = br.readLine()) != null){  
                    writer.println(cmd);  
                    writer.flush();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}


基数排序 基数排序 基数排序
/*
	待排数组:data_array[] = {6, 11, 33, 7, 10, 4, 21};
	对data_array中的每个数对10求余,并将余数放入二维数组redix_array中
	--------------------------------------------------------
	redix_array(方框号内的数字代表求余后的index):
	[0]: 10
    [1]: 11, 21
	[2]: 0
	[3]: 33
	[4]: 4
	[5]: 0
	[6]: 6
	[7]: 7
	[8]: 0
	[9]: 0
	--------------------------------------------------------
	将redix_array中的数从上到下,从左到右依次放入data_array中
	data_array = {10, 11, 21, 33, 4, 6, 7}
	对data_array中的每个数的十位进行求余,并将余数放入redix_array中
	--------------------------------------------------------
	redix_array:
	[0]: 4, 6, 7
	[1]: 10, 11
	[2]: 21
	[3]: 33
	[4]: 0
	[5]: 0
	[6]: 0
	[7]: 0
	[8]: 0
	[9]: 0
	--------------------------------------------------------
	再次将redix_array中的数一次插入到data_array中,即:
	4, 6, 7, 10, 11, 21, 33(排序结束)

	算法复杂度为(数组的长度 + 数组长度(从redix_array收集所有数字放入data_array中
	)) * 数组中最大位数(维数) 即 O(2 * d * n)
*/

#include <stdio.h>

static int get_index(int number, int count)
{
	int tmp_number = 1;
	for(int i = 0; i < count; ++i)
		tmp_number *= 10;
	return number / tmp_number % 10;
}

void redix_sort(int data_array[], int len)
{
	// 最大求余次数
	const int k = 10;
	// 基数的范围
	const int redix_num = 10;

	int redix_array[redix_num][len + 1];
	for(int index = 0; index < redix_num; ++index)
	{
		// 初始化计数变量
		redix_array[index][0] = 0;
	}
	
	for(int i = 0; i < k; ++i)
	{
		for(int j = 0, index; j < len; ++j)
		{
			index = get_index(data_array[j], i);
			redix_array[index][++redix_array[index][0]] = data_array[j];
		}

		for(int index = 0, j = 0; index < redix_num; ++index)
		{
			for(int k = 1; k <= redix_array[index][0]; ++k)
			{
				data_array[j++] = redix_array[index][k];
			}
			// 将计数变量清0
			redix_array[index][0] = 0;
		}
	}
}

void main()
{
	int data_array[] = {5, 1, 33, 4, 100, 5};
	redix_sort(data_array , 6);
	for(int i = 0; i < 6; ++i)
		printf("%d ", data_array[i]);
}


运行结果: 1 4 5 5 33 100















字节数组 与 十六进制间的转换 字节数组 与 十六进制间的转换 字节数组 与 十六进制间的转换
package com.test;
import java.util.Arrays;
public class Bytes {
	private final static byte[] hex = "0123456789ABCDEF".getBytes();
	private static int parse(char c) {
		if (c >= 'a')
			return (c - 'a' + 10) & 0x0f;
		if (c >= 'A')
			return (c - 'A' + 10) & 0x0f;
		return (c - '0') & 0x0f;
	}
	// 从字节数组到十六进制字符串转换
	public static String Bytes2HexString(byte[] b) {
		byte[] buff = new byte[2 * b.length];
		for (int i = 0; i < b.length; i++) {
			buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
			buff[2 * i + 1] = hex[b[i] & 0x0f];
		}
		return new String(buff);
	}
	// 从十六进制字符串到字节数组转换
	public static byte[] HexString2Bytes(String hexstr) {
		byte[] b = new byte[hexstr.length() / 2];
		int j = 0;
		for (int i = 0; i < b.length; i++) {
			char c0 = hexstr.charAt(j++);
			char c1 = hexstr.charAt(j++);
			b[i] = (byte) ((parse(c0) << 4) | parse(c1));
		}
		return b;
	}
	public static void main(String[] args) {
		byte[] bt = new byte[]{10, 2, 12, 14, 1, 0, 0, 1, 0, 31, 45, 1, 8, 0, 1, 0, -96, -45, 10, 3};
		System.out.println(Bytes2HexString(bt));
		System.out.println(Arrays.toString(HexString2Bytes("0A020C0E01000001001F2D0108000100A0D30A03")));
	}
}
poi 解析word 使用poi解析office文档(ppt,word,excel)属性,内容,图片等信息
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;


import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hslf.HSLFSlideShow;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.usermodel.PictureData;
import org.apache.poi.hslf.usermodel.SlideShow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFPictureData;
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.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.Range;

/**
 * 使用poi 解析office文档
 * @author longhuiping
 *
 */
public class OfficeParse {

	public static int count = 1;
	/**
	 * 解析word文档
	 * @param docPath	.doc文档路径
	 * @param imgSavePath	图片的保存地址
	 * @throws Exception
	 */
	public static void docParse( String docPath, String imgSavePath ) throws Exception
	{
		InputStream input = null;
		File docFile = new File( docPath );
		HWPFDocument document = null;
		try{
			//加载 doc 文档
			input = new FileInputStream( docFile );
			document = new HWPFDocument( input );
			
			DocumentSummaryInformation docInfo = document.getDocumentSummaryInformation();
			SummaryInformation sumInfo = document.getSummaryInformation();
			showInfo( sumInfo, docInfo );
			
			//内容
			Range range = document.getRange();
			String content = range.text();
			System.out.println( "内容:" + content );
			
			//获取所有的图片信息
			List pics = document.getPicturesTable().getAllPictures();
			for( int i = 0; i < pics.size(); i++ )
			{
				Picture pic = ( Picture ) pics.get( i );
				if( null != pic )
				{
					FileOutputStream output = new FileOutputStream( new File( imgSavePath + count + "." + pic.suggestFileExtension()) );
					pic.writeImageContent( output );
					output.close();
					count++;
				}
			}
			
		}catch( Exception e)
		{
			throw e;
		}finally{
			if( null != input )
				input.close();
		}
	}
	
	/**
	 * 解析ppt文档
	 * @param pptPath  文档路径
	 * @param imgSavePath	图片保存路径
	 * @throws Exception
	 */
	public static void pptParse( String pptPath, String imgSavePath ) throws Exception
	{
		InputStream input = null;
		HSLFSlideShow document = null;
		try{
			
			//加载ppt文档
			input = new FileInputStream( pptPath );
			document = new HSLFSlideShow( input );
			
			/** 获取ppt属性信息 **/
			DocumentSummaryInformation docInfo = document.getDocumentSummaryInformation();
			SummaryInformation sumInfo = document.getSummaryInformation();
			showInfo( sumInfo, docInfo );
			
			/** 获取ppt内容 **/
			StringBuilder pptContent = new StringBuilder();
			SlideShow slideShow = new SlideShow( document );
			Slide [] slides = slideShow.getSlides(); 
			int slideLength = slides.length;
			for( int i = 0; i < slideLength; i++ )
			{
				//获取每张ppt页面的标题
				Slide slide = slides[i];
				pptContent.append( slide.getTitle() );
				//获取每张ppt页面的内容
				TextRun [] trs = slide.getTextRuns();
				if( null != trs && 0 != trs.length )
				{
					int trsLength = trs.length;
					for( int j = 0; j < trsLength; j++ )
					{
						TextRun tr = trs[j];
						pptContent.append( tr.getText() );
					}
				}
			}
			System.out.println( "内容:" + pptContent.toString() );
			
			/** 获取 ppt中的图片 **/
			PictureData [] picDatas = slideShow.getPictureData();
			int picDatasLength = picDatas.length;
			for( int i = 0; i < picDatasLength; i++ )
			{
				PictureData picData = picDatas[i];
				byte [] bytes = picData.getData();
				FileOutputStream output = new FileOutputStream( imgSavePath + count + "."+ getPictureSuffix( picData ) );
				BufferedOutputStream writer = new BufferedOutputStream( output ) ;
				writer.write( bytes );
				writer.flush();
				writer.close();
				output.close();
				count++;
			}
		}catch( Exception e)
		{
			throw e;
		}finally{
			if( null != input )
				input.close();
			
		}
	}
	
	/**
	 * 解析excel文档
	 * @param xlsPath  文档路径
	 * @param imgSavePath  图片保存路径
	 * @throws Exception
	 */
	public static void xlsParse( String xlsPath, String imgSavePath ) throws Exception
	{
		InputStream input = null;
		HSSFWorkbook workbook = null;
		try{
			//加载文档
			input = new FileInputStream( xlsPath );
			workbook = new HSSFWorkbook( input );
			/** 获取文档属性 **/
			DocumentSummaryInformation docInfo = workbook.getDocumentSummaryInformation();
			SummaryInformation sumInfo = workbook.getSummaryInformation();
			showInfo( sumInfo, docInfo );
			
			/** 获取文档内容 因为excel采用的是单元格格式 所以采用循环取单元格的值**/
			StringBuilder xlsContent = new StringBuilder();
			//获取工作表数量
			int sheetTotal = workbook.getNumberOfSheets();
			//获取工作表信息
			for( int i = 0;  i < sheetTotal; i++ )
			{
				
				HSSFSheet sheet = workbook.getSheetAt( i );
				if( null == sheet )
					continue;
				int rowTotal = sheet.getLastRowNum();
				//获取 行信息
				for( int j = 0; j < rowTotal; j++ )
				{
					HSSFRow row = sheet.getRow( j );
					if( null == row )
						continue;
					int cellTotal = row.getLastCellNum() ;
					//获取单元格信息
					for( int k = 0; k < cellTotal; k++ )
					{
						HSSFCell cell = row.getCell( k );
						if( null == cell )
							continue;
						xlsContent.append( cell.toString() );
					}
				}
			}
			System.out.println( "内容:" + xlsContent.toString() );
			
			/** 获取图片信息 **/
			List<HSSFPictureData> picDatas = workbook.getAllPictures();
			int picDatasSize = picDatas.size();
			for( int i = 0; i < picDatasSize; i++ )
			{
				HSSFPictureData picData = picDatas.get( i );
				if( null == picData ) continue;
				byte [] bytes = picData.getData();
				FileOutputStream output = new FileOutputStream( imgSavePath + count + "."+ picData.suggestFileExtension() );
				BufferedOutputStream writer = new BufferedOutputStream( output ) ;
				writer.write( bytes );
				writer.flush();
				writer.close();
				output.close();
				count++;
			}
		}catch( Exception e)
		{
			throw e;
		}finally{
			if( null != input )
				input.close();
			
		}
	}
	public static void showInfo( SummaryInformation sumInfo, DocumentSummaryInformation docInfo ) throws Exception
	{
		/** 摘要信息 **/
		System.out.println("标题:" + sumInfo.getTitle());
		System.out.println("主题:" + sumInfo.getSubject());
		System.out.println("作者:" + sumInfo.getAuthor());
		System.out.println("关键字:" + sumInfo.getKeywords());
		
		System.out.println("备注:" + sumInfo.getComments());
		System.out.println("模板:" + sumInfo.getTemplate());
		System.out.println("上次保存用户:" + sumInfo.getLastAuthor());
		System.out.println("修订次数:" + sumInfo.getRevNumber());
		
		System.out.println("编辑文档的时间:" + sumInfo.getEditTime());
		System.out.println("打印时间:" + sumInfo.getLastPrinted());
		System.out.println("创建时间:" + sumInfo.getCreateDateTime());
		System.out.println("上一次保存时间:" + sumInfo.getLastSaveDateTime());
		
		System.out.println("页面数量:" + sumInfo.getPageCount());
		System.out.println("字数:" + sumInfo.getWordCount());
		System.out.println("字符数:" + sumInfo.getCharCount());
		System.out.println("应用软件名称:" + sumInfo.getApplicationName());
		
		/** 文档信息 部分属性属于个别office文档类型特有的属性 **/
		System.out.println("类别:" + docInfo.getCategory() );
		System.out.println("显示的格式:" + docInfo.getPresentationFormat() );
		System.out.println("字节数:" + docInfo.getByteCount() );
		System.out.println("行数:" + docInfo.getLineCount() );
		
		
		System.out.println("段落数:" + docInfo.getParCount() );
		System.out.println("幻灯片的数量:" + docInfo.getSlideCount() );
		System.out.println("备注数量:" + docInfo.getNoteCount() );
		System.out.println("隐藏文件的数量:" + docInfo.getHiddenCount() );
		
		System.out.println("多媒体剪辑数量:" + docInfo.getMMClipCount() );
		System.out.println("经理:" + docInfo.getManager() );
		System.out.println("单位:" + docInfo.getCompany() );
		System.out.println("链接:" + docInfo.getLineCount() );
	}
	
	/**
	 * 获取ppt文档中的图片格式
	 * @param pictureData
	 * @return
	 * @throws Exception
	 */
	public static String getPictureSuffix( PictureData pictureData ) throws Exception
	{
		String suffix = "";
		int tp = pictureData.getType();
		switch( tp ){
			case org.apache.poi.hslf.model.Picture.DIB:
				suffix = "dib";
				break;
			case org.apache.poi.hslf.model.Picture.EMF:
				suffix = "emf";
				break;
			case org.apache.poi.hslf.model.Picture.JPEG:
				suffix = "jpeg";
				break;
			case org.apache.poi.hslf.model.Picture.PICT:
				suffix = "pict";
				break;
			case org.apache.poi.hslf.model.Picture.PNG:
				suffix = "png";
				break;
			case org.apache.poi.hslf.model.Picture.WMF:
				suffix = "wmf";
				break;
			
		}
		return suffix;
	}

	public static void main( String [] args ) throws Exception
	{
		String imgSavePath = "f:/pdfimg/";
		docParse("f:/1.doc", imgSavePath );
		pptParse("f:/ppt/1.ppt", imgSavePath );
		xlsParse("f:/xls/1.xls", imgSavePath );
	}
Global site tag (gtag.js) - Google Analytics