java 文件压缩 base64加解密 生成指定随机数 时间换算 获取系统 获取mac等小结

平常开发中会遇到一些小而有用的程序,可以拿过来就用的,现整理如下

首先,是比较杂乱的小方法

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class util {

	/**
	 * 生成min至max之间的随机数
	 * @param min最小值
	 * @param max最大值
	 * @return
	 */
	public static int suiJi(int min	,int max){
        Random random = new Random();
        int s = random.nextInt(max)%(max-min+1) + min;
        System.out.println(s);
		return s;
	}
	
	/**
	 * 获取指定时间前一天是几号
	 * @throws ParseException
	 */
	public static void data() throws ParseException{
		String str = "2015-03-01";
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		long l1 = df.parse(str).getTime();
		String str2 = df.format(l1-1);
		System.out.println(str2);
	}
	
	/**
	 * jdk自带的base64加解密算法方便实用
	 * @param str 
	 * @return
	 */
	public static String jiaJieMi(String str){
		BASE64Encoder base64 = new BASE64Encoder();//加密方法
		BASE64Decoder bd = new BASE64Decoder();//解密方法
		String a = base64.encode(str.getBytes());
		System.out.println("加密后############" + a);
		try {
			byte[] aa=bd.decodeBuffer(a);
			System.out.println("解密后############" +new String( aa,"utf-8"));
		} catch (IOException e) {
		}
		return null;
	}
	
	/**
	 * 文件压缩
	 * @param path
	 * @throws Exception
	 */
	public static void yaSuo(String path) throws Exception {
		File f = new File(path);
		FileInputStream fis = new FileInputStream(f);
		BufferedInputStream bis = new BufferedInputStream(fis);
		byte[] buf = new byte[1024];
		int len;
		FileOutputStream fos = new FileOutputStream("D:\\note.zip");
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		ZipOutputStream zos = new ZipOutputStream(bos);// 压缩包
		ZipEntry ze = new ZipEntry(f.getName());// 这是压缩包名里的文件名
		zos.putNextEntry(ze);// 写入新的 ZIP 文件条目并将流定位到条目数据的开始处

		while ((len = bis.read(buf)) != -1) {
			zos.write(buf, 0, len);
			zos.flush();
		}
		bis.close();
		zos.close();
	}
	
	public static void main(String[] args) {
//		suiJi(15,18);
//		jiaJieMi("加解密");
//		try {
//			yaSuo("E:\\222\\123.jpg");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
	}
}

接着,大多数时候对时间的换算比较麻烦,接下来这种方法会解决这个问题

/*
 *java中对日期的加减操作
 *gc.add(1,-1)表示年份减一.
 *gc.add(2,-1)表示月份减一.
 *gc.add(3.-1)表示周减一.
 *gc.add(5,-1)表示天减一.
 *以此类推应该可以精确的毫秒吧.没有再试.大家可以试试.
 *GregorianCalendar类的add(int field,int amount)方法表示年月日加减.
 *field参数表示年,月.日等.
 *amount参数表示要加减的数量.
 *
 * UseDate.java 测试如下:
 */
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;

public class UseDate {
	Date d = new Date();
	GregorianCalendar gc = new GregorianCalendar();
	SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

	public String getYears() {
		gc.setTime(d);
		gc.add(1, +1);
		gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc
				.get(Calendar.DATE));
		return sf.format(gc.getTime());
	}

	public String getHalfYear() {
		gc.setTime(d);
		gc.add(2, +6);
		gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc
				.get(Calendar.DATE));
		return sf.format(gc.getTime());
	}

	public String getQuarters() {
		gc.setTime(d);
		gc.add(2, +3);
		gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc
				.get(Calendar.DATE));
		return sf.format(gc.getTime());
	}

	public String getLocalDate() {
		return sf.format(d);
	}

	public static void main(String[] args) {
		UseDate ud = new UseDate();
		System.out.println(ud.getLocalDate());
		System.out.println(ud.getYears());
		System.out.println(ud.getHalfYear());
		System.out.println(ud.getQuarters());
	}
}

再次,是关于获取系统并且得到mac地址值的工具

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.net.InetAddress;  
import java.net.NetworkInterface;  
      
    /** 
     * 与系统相关的一些常用工具方法. 
     */  
public class SystemTool {  
      
        /** 
         * 获取当前操作系统名称. return 操作系统名称 例如:windows xp,linux 等. 
         */  
        public static String getOSName() {  
            return System.getProperty("os.name").toLowerCase();  
        }  
      
        /** 
         * 获取unix网卡的mac地址. 非windows的系统默认调用本方法获取. 
         * 如果有特殊系统请继续扩充新的取mac地址方法. 
         *  
         * @return mac地址 
         */  
        public static String getUnixMACAddress() {  
            String mac = null;  
            BufferedReader bufferedReader = null;  
            Process process = null;  
            try {  
                // linux下的命令,一般取eth0作为本地主网卡  
                process = Runtime.getRuntime().exec("ifconfig eth0");  
                // 显示信息中包含有mac地址信息  
                bufferedReader = new BufferedReader(new InputStreamReader(  
                        process.getInputStream()));  
                String line = null;  
                int index = -1;  
                while ((line = bufferedReader.readLine()) != null) {  
                    // 寻找标示字符串[hwaddr]  
                    index = line.toLowerCase().indexOf("hwaddr");  
                    if (index >= 0) {// 找到了  
                        // 取出mac地址并去除2边空格  
                        mac = line.substring(index + "hwaddr".length() + 1).trim();  
                        break;  
                    }  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            } finally {  
                try {  
                    if (bufferedReader != null) {  
                        bufferedReader.close();  
                    }  
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
                bufferedReader = null;  
                process = null;  
            }  
            return mac;  
        }  
      
        /** 
         * 获取widnows网卡的mac地址. 
         *  
         * @return mac地址 
         */  
        public static String getWindowsMACAddress() {  
            String mac = null;  
            BufferedReader bufferedReader = null;  
            Process process = null;  
            try {  
                // windows下的命令,显示信息中包含有mac地址信息  
                process = Runtime.getRuntime().exec("ipconfig /all");  
                bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));  
                String line = null;  
                int index = -1;  
                while ((line = bufferedReader.readLine()) != null) {  
                    System.out.println(line);  
                    // 寻找标示字符串[physical  
                    index = line.toLowerCase().indexOf("physical address");  
                      
                    if (index >= 0) {// 找到了  
                        index = line.indexOf(":");// 寻找":"的位置  
                        if (index >= 0) {  
                            System.out.println(mac);  
                            // 取出mac地址并去除2边空格  
                            mac = line.substring(index + 1).trim();  
                        }  
                        break;  
                    }  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            } finally {  
                try {  
                    if (bufferedReader != null) {  
                        bufferedReader.close();  
                    }  
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
                bufferedReader = null;  
                process = null;  
            }  
      
            return mac;  
        }  
      
        /** 
         * windows 7 专用 获取MAC地址 
         *  
         * @return 
         * @throws Exception 
         */  
        public static String getMACAddress() throws Exception {  
              
            // 获取本地IP对象  
            InetAddress ia = InetAddress.getLocalHost();  
            // 获得网络接口对象(即网卡),并得到mac地址,mac地址存在于一个byte数组中。  
            byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();  
      
            // 下面代码是把mac地址拼装成String  
            StringBuffer sb = new StringBuffer();  
      
            for (int i = 0; i < mac.length; i++) {  
                if (i != 0) {  
                    sb.append("-");  
                }  
                // mac[i] & 0xFF 是为了把byte转化为正整数  
                String s = Integer.toHexString(mac[i] & 0xFF);  
                sb.append(s.length() == 1 ? 0 + s : s);  
            }  
      
            // 把字符串所有小写字母改为大写成为正规的mac地址并返回  
            return sb.toString().toUpperCase();  
        }  
      
        /** 
         * 测试用的main方法. 
         *  
         * @param argc 运行参数. 
         * @throws Exception 
         */  
        public static void main(String[] argc) throws Exception {  
            String os = getOSName();  
            System.out.println(os);  
            if (os.equals("windows 7")) {  
                String mac = getMACAddress();  
                System.out.println(mac);  
            } else if (os.startsWith("windows")) {  
                // 本地是windows  
                String mac = getWindowsMACAddress();  
                System.out.println(mac);  
            } else {  
                // 本地是非windows系统 一般就是unix  
                String mac = getUnixMACAddress();  
                System.out.println(mac);  
            }  
        }  
    }  

最后,是一个对配置文件读取的一小段代码

peizhi.properties

#文件是否删除 0不删 1删
filedel=0
#文件路径
filespath=E\:\\apache-tomcat-7.0.39\\webapps
读取

import java.io.IOException;
import java.util.Properties;

import org.springframework.core.io.support.PropertiesLoaderUtils;

public class peizhitest {

	public static void main(String[] args) throws IOException {
		Properties props =PropertiesLoaderUtils.loadAllProperties("peizhi.properties");
		String filedel= (String) props.get("filedel");
		String filespath= (String) props.get("filespath");
		System.out.println(filedel);
		System.out.println(filespath);
		if(filedel.equals("1")){
			System.out.println("删除");
		}
	}
}

关于文件的处理,还有一些简单的加密等工具,后续再整理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

做个文艺程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值