java 判断格式


/**
*判断是否是数字
*/
public static boolean isNum(String str){
        return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
    }

    /**
     * 判断是否是时间
     * @param str
     * @return
     */
    public static boolean isTime(String str){
        return str.matches("^[-+]?(([0-9]+)([:]([0-9]+))?|([:]([0-9]+))?)$");
    }

    /**
     * 将数字格式字符串改为保留两位小数,将时间格式字符串分钟保留两位数
     * @param str
     * @return
     */
    public static String stringFormat(String str){
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        if (isNum(str)) {
            str = nf.format(Double.parseDouble(str));
        } else if (isTime(str)) {
            String[] rowStr = str.split(":");
            if (rowStr.length > 1) {
                if (rowStr[1].length()>2) {
                    str = rowStr[0] + ":" + rowStr[1].substring(0, 2);
                }
            }
        }
        return str;
    }
<pre name="code" class="java">//   十六进制字符串转化成字节数组 每两位字符串转成一个字节
 
<pre name="code" class="java">public static byte[] hexStr2ByteArray(String hexString) {
        if (StringUtils.isEmpty(hexString))
            throw new IllegalArgumentException("this hexString must not be empty");

        hexString = hexString.toLowerCase();
        final byte[] byteArray = new byte[hexString.length() / 2];
        int k = 0;
        for (int i = 0; i < byteArray.length; i++) {
            //因为是16进制,最多只会占用4位,转换成字节需要两个16进制的字符,高位在先
            //将hex 转换成byte   "&" 操作为了防止负数的自动扩展
            // hex转换成byte 其实只占用了4位,然后把高位进行右移四位
            // 然后“|”操作  低四位 就能得到 两个 16进制数转换成一个byte.
            byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
            byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
            byteArray[i] = (byte) (high << 4 | low);
            System.out.print(byteArray[i]+":"+hexString.substring(2*i,2*(i+1))+".");
            k += 2;
        }
        return byteArray;
    }
/**
 *时间工具类
**/
package com.geetion.system.collection.jt808.tool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
    private static transient final Logger LOGGER = LoggerFactory.getLogger(DateUtil.class);

    /**
     * 格式:yyyy
     */
    public static SimpleDateFormat YEARFORMATER() {
        return new SimpleDateFormat("yyyy");
    }

    /**
     * 格式:yyyyMM
     */
    public static SimpleDateFormat MONTHFORMATER() {
        return new SimpleDateFormat("yyyyMM");
    }

    /**
     * 格式:yyyy年MM月
     */
    public static SimpleDateFormat MONTHFORMATERSTR() {
        return new SimpleDateFormat("yyyy年MM月");
    }

    /**
     * 格式:yyyyMMdd
     */
    public static SimpleDateFormat DATEFORMATER() {
        return new SimpleDateFormat("yyyyMMdd");
    }

    /**
     * 格式:yyyy年MM月dd日
     */
    public static SimpleDateFormat DATEFORMATER1() {
        return new SimpleDateFormat("yyyy年MM月dd日");
    }

    /**
     * 格式:yyyy-MM-dd
     */
    public static SimpleDateFormat DATEFORMATER2() {
        return new SimpleDateFormat("yyyy-MM-dd");
    }

    /**
     * 格式:MM-dd HH:mm
     */
    public static SimpleDateFormat DATEFORMATER3() {
        return new SimpleDateFormat("yyMMddHHmmss");
    }

    /**
     * 格式:yyyyMMdd-HH:mm:ss
     */
    public static SimpleDateFormat TIMEFORMATER() {
        return new SimpleDateFormat("yyyyMMdd-HH:mm:ss");
    }

    /**
     * 格式:yyyy-MM-dd HH:mm:ss
     */
    public static SimpleDateFormat TIMEFORMATER1() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 格式:yyMMddHHmmss
     */
    public static SimpleDateFormat TIMEFORMATER3() {
        return new SimpleDateFormat("yyMMddHHmmss");
    }

    /**
     * 格式:MM-dd HH:mm
     */
    public static SimpleDateFormat TIMEFORMATER4() {
        return new SimpleDateFormat("MM-dd HH:mm");
    }

    /**
     * 格式:yyyyMMddHHmmss
     */
    public static SimpleDateFormat TIMEFORMATER_yyyyMMddHHmmss() {
        return new SimpleDateFormat("yyyyMMddHHmmss");
    }

    public static Date formatTime(String timeStr) {

        Date date = null;
        try {
            date = TIMEFORMATER().parse(timeStr);
        } catch (Exception e) {
            String errorMsg = String.format("解析日期失败,非法的日期格式[%s], 正确格式为[yyyyMMdd-HH:mm:ss]", timeStr);
            LOGGER.trace(errorMsg);
        }

        return date;
    }
    public static Date stringToDatetime(String timeStr){
    	
    	Date date = null;
    	try {
    		date = TIMEFORMATER1().parse(timeStr);
    	} catch (Exception e) {
    		String errorMsg = String.format("解析日期失败,非法的日期格式[%s], 正确格式为[yyyy-MM-dd HH:mm:ss]", timeStr);
    		LOGGER.trace(errorMsg);
    	}
    	
    	return date;
    }

    public static Date formatDate(String dateStr) {

        Date date = null;
        try {
            date = DATEFORMATER().parse(dateStr);
        } catch (Exception e) {
            String errorMsg = String.format("解析日期失败,非法的日期格式[%s]", dateStr);
            LOGGER.trace(errorMsg);
        }

        return date;
    }

    public static Date formatDate(Date date) {

        String dateString = DATEFORMATER().format(date);
        Date formatedDate = null;
        try {
            formatedDate = DATEFORMATER().parse(dateString);
        } catch (Exception e) {
            LOGGER.trace(e.getMessage());
            e.printStackTrace();
        }

        return formatedDate;
    }

    public static Date addHour(Date date, int hour) {

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.HOUR, hour);

        return c.getTime();
    }

    public static Date addDate(Date date, int day) {

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, day);

        return c.getTime();
    }

    public static Date formatMonth(Date date) {

        String dateString = MONTHFORMATER().format(date);
        Date formatedDate = null;
        try {
            formatedDate = MONTHFORMATER().parse(dateString);
        } catch (Exception e) {
            LOGGER.trace(e.getMessage());
            e.printStackTrace();
        }

        return formatedDate;
    }

    public static Date addMonth(Date date, int month) {

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.MONTH, month);

        return c.getTime();
    }

    public static Date formatYear(Date date) {

        String dateString = YEARFORMATER().format(date);
        Date formatedDate = null;
        try {
            formatedDate = YEARFORMATER().parse(dateString);
        } catch (Exception e) {
            LOGGER.trace(e.getMessage());
            e.printStackTrace();
        }

        return formatedDate;
    }

    public static Date addYear(Date date, int year) {

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.YEAR, year);

        return c.getTime();
    }

    public static String stratTimeToday(Date date) {

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);

        return TIMEFORMATER1().format(c.getTime());
    }

    public static String endTimeToday(Date date) {

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);

        return TIMEFORMATER1().format(c.getTime());
    }

    public static boolean isToday(Date date) {

        Date today = formatDate(new Date());
        date = formatDate(date);

        return (today.getTime() == date.getTime());
    }

    public static boolean isCurMonth(Date date) {

        Date today = formatMonth(new Date());
        date = formatMonth(date);

        return (today.getTime() == date.getTime());
    }

    public static boolean isCurYear(Date date) {

        Date curYear = formatYear(new Date());
        date = formatMonth(date);

        return (curYear.getTime() == date.getTime());
    }

    public static Date getCalendarStart(Date date) {

        Date firstDay = formatMonth(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(firstDay);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

        return addDate(firstDay, 1 - dayOfWeek);
    }

    public static Date getCalendarEnd(Date date) {

        Date firstDay = formatMonth(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(firstDay);
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DATE, -1);

        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        calendar.add(Calendar.DATE, Calendar.DAY_OF_WEEK - dayOfWeek);

        return calendar.getTime();
    }

    public static Date getStarDateByYear(int year) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }

    public static Date getEndDateByYear(int year) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year + 1);
        c.set(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }

    /**
     * 求两个日期差 endDate - beginDate
     * 
     * @param beginDate
     *            开始日期
     * @param endDate
     *            结束日期
     * @return 两个日期相差天数
     */
    public static long getDateMargin(Date beginDate, Date endDate) {
        long margin = 0;
        margin = endDate.getTime() - beginDate.getTime();
        margin = margin / (1000 * 60 * 60 * 24);
        return margin;
    }

    public static void main(String[] args) throws ParseException {
        System.out.println(TIMEFORMATER1().format(getStarDateByYear(2013)));
        
        Date d = stringToDatetime("2015-04-07 14:00:00");
        Date d1 = stringToDatetime("2015-04-07 14:01:00");
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        System.out.println(c.get(Calendar.YEAR));
        System.out.println(getSeconds(d,d1));
    }
    
    public static Date getDate(Date date, int field, int i) {

		if (date == null)
			return null;

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(field, i);

		return calendar.getTime();

	}
    
    public static double getSeconds(Date start, Date end)
    {
        double diffInSeconds = 0.001 * (end.getTime() - start.getTime());
        return diffInSeconds;
    }
    
}



 

### 如何在Java判断文件格式 为了确定文件的格式,在Java中有多种方法可以实现这一功能。一种常见的做法是通过读取文件头(即文件签名),因为许多类型的文件在其开头部分存储有特定字节序列来标识其类型[^1]。 下面是一个简单的例子,展示如何基于文件头部信息识别一些常见图像文件格式: ```java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class FileFormatDetector { public static String detectImageFileType(Path filePath) throws IOException { byte[] headerBytes = Files.readAllBytes(filePath); if (headerBytes.length >= 4) { // Ensure enough bytes to check signatures // Check JPEG signature if ((headerBytes[0] & 0xFF) == 0xFF && (headerBytes[1] & 0xFF) == 0xD8 && (headerBytes[2] & 0xFF) == 0xFF) { return "JPEG"; } else if (headerBytes[0] == 'G' && headerBytes[1] == 'I' && headerBytes[2] == 'F' && headerBytes[3] == '8') { // Check GIF signature return "GIF"; } else if (headerBytes[0] == 0x89 && headerBytes[1] == 'P' && headerBytes[2] == 'N' && headerBytes[3] == 'G') { // Check PNG signature return "PNG"; } } return "Unknown"; } } ``` 此代码片段展示了如何检测几种流行的图片格式——JPEG、GIF 和 PNG 的文件头,并返回相应的字符串表示形式。当然,这种方法也可以扩展到其他类型的文件上,只需知道它们各自的魔数即可。 对于更复杂的场景或更多种类的文件支持,则可能需要借助第三方库的帮助,比如 Apache Tika 或者 JMimeMagic 等工具包,这些库提供了更为全面的功能用于自动探测各种不同类型的文档、音频视频等资源的真实MIME类型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值