无需言 做自己 业 ,精于勤 荒于嬉.

PHP杂项 获取文章html中的img标签图片src地址

发表日期:2022-08-06 15:42:56 | 来源: | 分类:PHP杂项

      示例1
/**
 * 获取文章中的图片
 * @param $content
 * @return mixed
 */
function html_get_img($content)
{
//    强力模式
//    preg_match_all('#<[img|IMG].*?[src|SRC]=[$"|$\'|$\s]*([^"|^\'|^\s]*)[^>]*>#i', $content, $match);
    preg_match_all('#<[img].*?[src]="([^"]*)[^>]*>#i', $content, $match);
    return $match[1];
}

阅读全文 »

PHP杂项 html过滤标签空格提取纯文本text

发表日期:2022-08-06 15:41:37 | 来源: | 分类:PHP杂项

      示例1
/**
 * html 转换成text 过滤html标签空格
 * @param $html
 * @param null|string $html_tag 要保留的标签
 * @return string
 */
function html2text($html, $html_tag = null)
{
    return trim(preg_replace("/[ ]+/", " ", str_replace(["&nbsp;", " "], " ", strip_tags($html, $html_tag))));
}

阅读全文 »

PHP杂项 自实现http_build_url 函数

发表日期:2022-08-06 15:39:34 | 来源: | 分类:PHP杂项

      示例1
if (!function_exists('http_build_url')) {
    /**
     * 构建URL
     * @param string $url
     * @param array $params
     * @return string
     */
    function http_build_url($url, $params)
    {
        if (!strstr($url, '?')) $url .= "?";

        if (($last = strrchr($url, '&')) && $last !== '&') $url .= "&";

        return $url . http_build_query($params);
    }
}

阅读全文 »

PHP杂项 获取浏览器类型版本及操作系统类型

发表日期:2022-08-06 15:31:18 | 来源: | 分类:PHP杂项

      示例1
class Agent
{

    /**
     * 获取客户端浏览器信息 添加win10 edge浏览器判断
     * @param null
     * @return string
     */
    public static function getBroswer()
    {
        if (isset($_SERVER['HTTP_USER_AGENT']))
        {
            $sys = $_SERVER['HTTP_USER_AGENT'];  //获取用户代理字符串
        }else{
            $sys = '';  //获取用户代理字符串
        }

        if (stripos($sys, "Firefox/") > 0) {
            preg_match("/Firefox\/([^;)]+)+/i", $sys, $b);
            $exp[0] = "Firefox";
            $exp[1] = $b[1];  //获取火狐浏览器的版本号
        } elseif (stripos($sys, "Maxthon") > 0) {
            preg_match("/Maxthon\/([\d\.]+)/", $sys, $aoyou);
            $exp[0] = "傲游";
            $exp[1] = $aoyou[1];
        } elseif (stripos($sys, "MSIE") > 0) {
            preg_match("/MSIE\s+([^;)]+)+/i", $sys, $ie);
            $exp[0] = "IE";
            $exp[1] = $ie[1];  //获取IE的版本号
        } elseif (stripos($sys, "OPR") > 0) {
            preg_match("/OPR\/([\d\.]+)/", $sys, $opera);
            $exp[0] = "Opera";
            $exp[1] = $opera[1];
        } elseif (stripos($sys, "Edge") > 0) {
            //win10 Edge浏览器 添加了chrome内核标记 在判断Chrome之前匹配
            preg_match("/Edge\/([\d\.]+)/", $sys, $Edge);
            $exp[0] = "Edge";
            $exp[1] = $Edge[1];
        } elseif (stripos($sys, "Chrome") > 0) {
            preg_match("/Chrome\/([\d\.]+)/", $sys, $google);
            $exp[0] = "Chrome";
            $exp[1] = $google[1];  //获取google chrome的版本号
        } elseif (stripos($sys, 'rv:') > 0 && stripos($sys, 'Gecko') > 0) {
            preg_match("/rv:([\d\.]+)/", $sys, $IE);
            $exp[0] = "IE";
            $exp[1] = $IE[1];
        } elseif (stripos($sys, 'Safari') > 0) {
            preg_match("/safari\/([^\s]+)/i", $sys, $safari);
            $exp[0] = "Safari";
            $exp[1] = $safari[1];
        } elseif (stripos($sys, 'ApiPOST') !== false) {
            preg_match("/apipost\/([^\s]+)/i", $sys, $ApiPOST);
            $exp[0] = "ApiPOST";
            $exp[1] = "Runtime";
        } elseif (stripos($sys, 'PostmanRuntime') !== false) {
            preg_match("/PostmanRuntime\/([^\s]+)/i", $sys, $Postman);
            $exp[0] = "Postman";
            $exp[1] = $Postman[1];
        } elseif (stripos($sys, 'curl') !== false) {
            preg_match("/curl\/([^\s]+)/i", $sys, $curl);
            $exp[0] = "curl";
            $exp[1] = $curl[1];
        } else {
            $exp[0] = "未知";
            $exp[1] = "";
        }
        return $exp[0] . '(' . $exp[1] . ')';
    }

    /**
     * 获取客户端操作系统信息包括win10
     * @param null
     * @return string
     */
    public static function getOs()
    {
        if (isset($_SERVER['HTTP_USER_AGENT']))
        {
            $agent = $_SERVER['HTTP_USER_AGENT'];  //获取用户代理字符串
        }else{
            $agent = '';  //获取用户代理字符串
        }

        if (preg_match('/Windows Phone/i', $agent)) {
            $os = 'Windows Phone';
//        } else if (preg_match('/win/i', $agent) && strpos($agent, '95')) { 
//            $os = 'Windows 95';
//        } else if (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90')) {
//            $os = 'Windows ME';
//        } else if (preg_match('/win/i', $agent) && preg_match('/98/i', $agent)) {
//            $os = 'Windows 98';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) {
            $os = 'Windows Vista';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) {
            $os = 'Windows 7';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) {
            $os = 'Windows 8';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) {
            $os = 'Windows 10';#添加win10判断
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) {
            $os = 'Windows XP';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) {
            $os = 'Windows 2000';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) {
            $os = 'Windows NT';
        } else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) {
            $os = 'Windows 32';
        } else if (preg_match('/linux/i', $agent)) {
            $os = 'Linux';
        } else if (preg_match('/unix/i', $agent)) {
            $os = 'Unix';
        } else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) {
            $os = 'SunOS';
        } else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) {
            $os = 'IBM OS/2';
        } else if (preg_match('/Mac/i', $agent)) {
            $os = 'Mac';
        } else if (preg_match('/PowerPC/i', $agent)) {
            $os = 'PowerPC';
        } else if (preg_match('/AIX/i', $agent)) {
            $os = 'AIX';
        } else if (preg_match('/HPUX/i', $agent)) {
            $os = 'HPUX';
        } else if (preg_match('/NetBSD/i', $agent)) {
            $os = 'NetBSD';
        } else if (preg_match('/BSD/i', $agent)) {
            $os = 'BSD';
        } else if (preg_match('/OSF1/i', $agent)) {
            $os = 'OSF1';
        } else if (preg_match('/IRIX/i', $agent)) {
            $os = 'IRIX';
        } else if (preg_match('/FreeBSD/i', $agent)) {
            $os = 'FreeBSD';
        } else if (preg_match('/teleport/i', $agent)) {
            $os = 'teleport';
        } else if (preg_match('/flashget/i', $agent)) {
            $os = 'flashget';
        } else if (preg_match('/webzip/i', $agent)) {
            $os = 'webzip';
        } else if (preg_match('/offline/i', $agent)) {
            $os = 'offline';
        } elseif (preg_match('/ucweb|MQQBrowser|J2ME|IUC|3GW100|LG-MMS|i60|Motorola|MAUI|m9|ME860|maui|C8500|gt|k-touch|X8|htc|GT-S5660|UNTRUSTED|SCH|tianyu|lenovo|SAMSUNG/i', $agent)) {
            $os = 'mobile';
        } else {
            $os = '未知';
        }
        return $os;
    }
}

阅读全文 »

PHP杂项 curl请求及注意事项

发表日期:2022-08-06 15:26:25 | 来源: | 分类:PHP杂项

      示例1
    function post($data, $url)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);//连接超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);//请求超时时间
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, true);//POST请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        
        //设置header头信息
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json; charset=utf-8',//json请求
            'token:vXBrUZ7rWE5D4P4ENnwR6GFvaG2pVgul'//比如登录信息/token信息/session信息
        ]);

        $output = curl_exec($ch);

        if ($error_code = curl_errno($ch)) { //已经检查是否报错做进一步处理
            $err = $error_code . ' : ' . curl_error($ch);
            curl_close($ch);
            throw new Exception($err);
        }

        curl_close($ch);
        return $output;
    }

阅读全文 »

PHP杂项 二维数组排序

发表日期:2022-08-06 15:15:16 | 来源: | 分类:PHP杂项

      示例1
/**
 * 升序降序排序
 * @param $arr
 * @param $keys 要排序的字段
 * @param string $type asc desc
 * @return array
 */
function array_sort($arr, $keys, $type = 'asc')
{
    $keysvalue = $new_array = array();
    foreach ($arr as $k => $v) {
        $keysvalue[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($keysvalue);
    } else {
        arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}

阅读全文 »

PHP杂项 文件字节大小换算KB、MB、GB、TB

发表日期:2022-08-06 15:11:53 | 来源: | 分类:PHP杂项

      示例1
/**
 * 字节换算
 * @param int $size 字节长度
 * @param int $digits 要保留几位小数
 * @return string 转换后的文件大小
 */
function byteToSize($size, $digits = 2)
{
    if ($size == 0) return '0B';
    $unit = array('', 'K', 'M', 'G', 'T', 'P');
    // 单位数组,是必须1024进制依次的哦。
    $base = 1024;
    // 对数的基数
    $i = floor(log($size, $base));
    // 字节数对1024取对数,值向下取整。 return
    return round($size / pow($base, $i), $digits) . ' ' . $unit [$i] . 'B';
}

阅读全文 »

PHP杂项 数字金额转汉字大写

发表日期:2022-08-06 15:10:20 | 来源: | 分类:PHP杂项

      示例1
function amountToCn($num)
{
    $Decimal = $num - (int)$num;

    $c1 = "零壹贰叁肆伍陆柒捌玖";
    $c2 = "分角元拾佰仟万拾佰仟亿";
    //精确到分后面就不要了,所以只留两个小数位
    $num = round($num, 2);
    //将数字转化为整数
    $num = $num * 100;
    if (strlen($num) > 10) {
        return "金额太大,请检查";
    }
    $i = 0;
    $c = "";
    while (1) {
        if ($i == 0) {
            //获取最后一位数字
            $n = substr($num, strlen($num) - 1, 1);
        } else {
            $n = $num % 10;
        }
        //每次将最后一位数字转化为中文
        $p1 = substr($c1, 3 * $n, 3);
        $p2 = substr($c2, 3 * $i, 3);
        if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
            $c = $p1 . $p2 . $c;
        } else {
            $c = $p1 . $c;
        }
        $i = $i + 1;
        //去掉数字最后一位了
        $num = $num / 10;
        $num = (int)$num;
        //结束循环
        if ($num == 0) {
            break;
        }
    }
    $j = 0;
    $slen = strlen($c);
    while ($j < $slen) {
        //utf8一个汉字相当3个字符
        $m = substr($c, $j, 6);
        //处理数字中很多0的情况,每次循环去掉一个汉字“零”
        if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
            $left = substr($c, 0, $j);
            $right = substr($c, $j + 3);
            $c = $left . $right;
            $j = $j - 3;
            $slen = $slen - 3;
        }
        $j = $j + 3;
    }
    //这个是为了去掉类似23.0中最后一个“零”字
    if (substr($c, strlen($c) - 3, 3) == '零') {
        $c = substr($c, 0, strlen($c) - 3);
    }
    //将处理的汉字加上“整”
    if (empty($c)) {
        return "零元整";
    } else {
        if ($Decimal > 0){
            return $c ;
        }

        return $c . "整";
    }
}

阅读全文 »

PHP杂项 验证身份证号是否有效

发表日期:2022-08-06 15:05:56 | 来源: | 分类:PHP杂项

      示例1
public function isIdCard($id)
{
    $id = strtoupper($id);
    $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
    $arr_split = array();
    if (!preg_match($regx, $id)) {
        return FALSE;
    }
    if (15 == strlen($id)) //检查15位
    {
        $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
        @preg_match($regx, $id, $arr_split);
        //检查生日日期是否正确
        $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
        if (!strtotime($dtm_birth)) {
            return FALSE;
        } else {
            return TRUE;
        }
    } else      //检查18位
    {
        $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
        @preg_match($regx, $id, $arr_split);
        $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
        if (!strtotime($dtm_birth)) //检查生日日期是否正确
        {
            return FALSE;
        } else {
            //检验18位身份证的校验码是否正确。
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。
            $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            $sign = 0;
            for ($i = 0; $i < 17; $i++) {
                $b = (int)$id{$i};
                $w = $arr_int[$i];
                $sign += $b * $w;
            }
            $n = $sign % 11;
            $val_num = $arr_ch[$n];
            if ($val_num != substr($id, 17, 1)) {
                return FALSE;
            }
            else {
                return TRUE;
            }
        }
    }
}

阅读全文 »

PHP杂项 批量替换文件名

发表日期:2022-08-05 23:32:29 | 来源: | 分类:PHP杂项

      示例1
<?php
// 效果:
// [canquick影视www.canquick.com]兄弟连DVD国语配音中英字幕无水印01集.mp4 
// 兄弟连01集.mp4

$handle = @opendir('./');

while ($file = readdir($handle)) {
        // 将 "." 及 ".." 排除不显示
        if ($file != "." && $file != "..") {
            print_r($file);
            rename($file,str_replace(
                [
                    '[canquick影视www.canquick.com]',
                    'DVD国语配音中英字幕无水印',
                ],
                [
                    '',
                    '',
                ],
                $file
            ));
        }
    }
closedir($handle);
?>

阅读全文 »

PHP杂项 批量修改照片文件名日期排序

发表日期:2022-08-05 23:15:29 | 来源: | 分类:PHP杂项

      示例1
<?php

$dir = "D:\个人收藏\照片备份 - 副本\\";

$md5 = [];
$i = 0;
if ($handle = opendir($dir)) {
    while (($file = readdir($handle)) !== false) {

        if (!in_array($file, ['.', '..', ['1.php']]) && !is_dir($file)) {
            if ($file === '1.php') continue;

            if (!file_exists($file)) {
                var_dump($file);
            } else {

                if (false) {//是否转小写文件名
                    rename($file, strtolower($file));
                }

                if (true) {//程序主体
                    ++$i;

                    $index = str_pad($i, 3, "0", STR_PAD_LEFT);

                    $filectime = filectime($file);
                    $filemtime = filemtime($file);
                    $time = $filemtime < $filectime ? $filemtime : $filectime;
                    $EXTENSION = pathinfo($file, PATHINFO_EXTENSION);

                    @$exif_data = exif_read_data($file);

                    if (!empty($exif_data['DateTime'])) {
                        $exif_date = $exif_data['DateTime'];
                        $fileptime = strtotime($exif_date);
                        $time = $time < $fileptime ? $time : $fileptime;
                    }
                    // DateTimeDigitized

                    if (!empty($exif_data['DateTimeOriginal'])) {
                        $exif_date = $exif_data['DateTimeOriginal'];

                        $fileptime = strtotime($exif_date);
                        if ($fileptime == false) {
                            var_dump($file . "\t" . $exif_date . "\t" . $fileptime);

                        } else {
                            $time = $time < $fileptime ? $time : $fileptime;
                        }

                    }

//                    exit();
//                $filectime = date('Y-m-d H:i:s',$filectime);
//                $filemtime = date('Y-m-d H:i:s',$filemtime);
//                $time = date('Y-m-d H:i:s',$time);
//                var_dump( "$file    创建时间:$filectime     修改时间:$filemtime    取时间:$time" );

//                img_20150816_131130.jpg
                    $newfile = "IMG_" . date('Ymd_His', $time) . "." . $EXTENSION;

                    if (file_exists($newfile)) {
                        $newfile = "IMG_" . date('Ymd_His', $time) . "_" . $index . "." . $EXTENSION;
                    }
                    rename($file, $newfile);
//                    var_dump($newfile);
                }

                if (false) {//是否去重复
                    $file_md5 = md5_file($file);
                    if (isset($md5[$file_md5])) {
                        $repeat = $md5[$file_md5];

                        var_dump("$repeat   ->  $file");

                        $repeat_filectime = filectime($repeat);
                        $repeat_filemtime = filemtime($repeat);
                        $repeat_time = $repeat_filemtime < $repeat_filectime ? $repeat_filemtime : $repeat_filectime;


                        $filectime = filectime($file);
                        $filemtime = filemtime($file);
                        $time = $filemtime < $filectime ? $filemtime : $filectime;

                        if ($time <= $repeat_time) {
                            unlink($repeat);
                            $md5[$file_md5] = $file;
                        } else {
                            unlink($file);
                        }

                    } else {
                        $md5[$file_md5] = $file;
                    }
                }

                if (false) {//是否把照片归类到每天一个文件夹(事实发现同一天拍摄的照片大多是同一类)
                    $filectime = filectime($file);
                    $filemtime = filemtime($file);
                    $time = $filemtime < $filectime ? $filemtime : $filectime;

                    $_dir = date('Y-m-d', $time);

                    @mkdir($_dir);
                    if (!file_exists($_dir . '\\' . $file)) {
                        copy($file, $_dir . '\\' . $file);
                    }
                }
            }

        }
    }
    closedir($handle);
}


?>

阅读全文 »

JAVA基础 30.Camparable

发表日期:2022-08-05 16:54:10 | 来源: | 分类:JAVA基础

      示例1
class Student implements Comparable<Student>{
   private String name;
   private int age;
   private float score;
   
   public Student(String name,int age,float score){
      this.name = name;
      this.age = age;
      this.score = score;
   }
   
   public String toString(){
      return name + "\t\t" + this.age + "\t\t" + this.score;
   }
   public int compareTo(Student stu){
      if(this.score>stu.score){
         return -1;
      }else if(this.score<stu.score){
         return 1;
      }else{
         if(this.age>stu.age){
            return 1;
         }else if(this.age<stu.age){
            return -1;
         }else{
            return 0;
         }
      }
   }
}
public class CamparableDemo01 {

   public static void main(String args[]) {
      Student stu[] = {
            new Student("张三",20,90.0f),
            new Student("李四",21,92.0f),
            new Student("王五",24,88.3f),
            new Student("赵六",19,86.1f),
            new Student("孙七",23,76.1f)
      };
      for(int i=0;i<stu.length;i++){
         System.out.println(stu[i]);
      }
      
      java.util.Arrays.sort(stu);
      
      System.out.println("<<<<<<Campare>>>>>>");
      
      for(int i=0;i<stu.length;i++){
         System.out.println(stu[i]);
      }

   }

}

阅读全文 »

JAVA基础 25.JDBC

发表日期:2022-08-05 16:42:10 | 来源: | 分类:JAVA基础

      示例1
import java.sql.*;

class MySql {
    private String sql;

    private ResultSet result = null;

    private Connection conn = null;

    private PreparedStatement pstmt = null;

    private static String MM_myDb_DRIVER = "org.gjt.mm.mysql.Driver";
    private static String MM_myDb_USERNAME = "root";
    private static String MM_myDb_PASSWORD = "123456";
    private static String MM_myDb_STRING = "jdbc:mysql://localhost:3306/my_blog";

    public ResultSet run(String sql) {

        try {
            Class.forName(MM_myDb_DRIVER);
            conn = DriverManager.getConnection(MM_myDb_STRING, MM_myDb_USERNAME, MM_myDb_PASSWORD);
            this.sql = sql;
            pstmt = conn.prepareStatement(sql);
            result = pstmt.executeQuery();
        } catch (Exception e) {
            closeDb();
        }
        return result;
    }

    public void closeDb() {
        try {
            result.close();
            pstmt.close();
            conn.close();
        } catch (Exception e) {
        }
    }
}

public class MySqlDemo01 {

    public static void main(String args[]) {
        MySql ms = new MySql();
        ResultSet result = ms.run("SELECT id,title FROM content");
        try {
            while (result.next()) {
                System.out.println("编号:" + result.getString(1) + "----------------" + "标题:" + result.getString(2) + "<br/>");
            }
        } catch (Exception e) {
        } finally {
            ms.closeDb();
        }
    }
}

阅读全文 »

JAVA基础 29.Serializable

发表日期:2022-08-05 16:41:10 | 来源: | 分类:JAVA基础

      示例1
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;


public class Pet implements Externalizable{
   
   private static final long serialVersionUID = 1L;
   private String name ;
   private int age ;
   private String sex ;

   public Pet(){}
   
   public Pet(String name , int age , String sex){
      setName(name);
      setAge(age);
      setSex(sex);
   }

   public String toString() {
      return "姓名:"+name+" 年龄:"+age+" 性别:"+sex;
   }
   
   @Override
   public void readExternal(ObjectInput in) throws IOException,
         ClassNotFoundException {
      // TODO Auto-generated method stub
      setName((String) in.readObject());
      setAge(in.readInt());
      //setSex((String) in.readObject());  Sex就不会被保存
   }

   @Override
   public void writeExternal(ObjectOutput out) throws IOException {
      // TODO Auto-generated method stub
      out.writeObject(getName());
      out.writeInt(getAge());
      //out.writeObject(getSex());
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getName() {
      return name;
   }

   public void setAge(int age) {
      this.age = age;
   }

   public int getAge() {
      return age;
   }

   public void setSex(String sex) {
      this.sex = sex;
   }

   public String getSex() {
      return sex;
   }

}
      示例2
import java.io.Serializable;


public class Person implements Serializable{

   /**
    * 
    */
   private static final long serialVersionUID = 1L;
   
   private String name ;
   private int age ;
   private transient String sex ;//transient 声明的变量不会被序列号
   
   public Person(String name, int age , String sex) {
      // TODO Auto-generated constructor stub
      setName(name);
      setAge(age);
      setSex(sex);
   }

   public String toString() {
      return "姓名:"+name+" 年龄:"+age+" 性别:"+sex;
   }

   public void setName(String name) {
      this.name = name;
   }
   
   public String getName() {
      return name;
   }
   
   public void setAge(int age) {
      this.age = age;
   }
   
   public int getAge() {
      return age;
   }

   public void setSex(String sex) {
      this.sex = sex;
   }

   public String getSex() {
      return sex;
   }
   

}
      示例3
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;


public class ObjectOutputStreamDemo {

    /**
     * @param args
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // TODO Auto-generated method stub

        File file = new File("D:" + File.separator + "javademo.txt");


        OutputStream out = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(out);
        oos.writeObject(new Person("张三", 22, "男"));//性别不会被保存  transient 声明的变量不会被序列号


        InputStream in = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(in);
        Person person = (Person) ois.readObject();
        System.out.println(person.getName());
        System.out.println(person.getAge());
        System.out.println(person);

    }

}
      示例4
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;


public class ObjectOutputStreamDemo2 {

   /**
    * @param args
    * @throws IOException 
    * @throws ClassNotFoundException 
    */
   public static void main(String[] args) throws IOException, ClassNotFoundException {
      // TODO Auto-generated method stub
      
      File file = new File("D:"+File.separator+"javademo.txt");
      
      
      OutputStream out = new FileOutputStream(file);
      ObjectOutputStream oos = new ObjectOutputStream(out );
      oos.writeObject(new Pet("小白",3,"公"));//性别不会被保存  没有配置writeExternal / readExternal
      
      
      InputStream in = new FileInputStream(file);
      ObjectInputStream ois = new ObjectInputStream(in);
      Pet pet = (Pet) ois.readObject();
      System.out.println(pet.getName());
      System.out.println(pet.getAge());
      System.out.println(pet);

   }

}

阅读全文 »

JAVA基础 28.Interface

发表日期:2022-08-05 16:38:14 | 来源: | 分类:JAVA基础

      示例1
interface A{
   //接口中的方法不能被实现,或者说必须全部是抽象方法
   //接口不能实现接口,而是继承父接口
   //实现接口的类,必须复写并实现接口的全部方法。除非是抽象类且是抽象方法。
   public abstract void print();
   public void printr();
   public void printf();
}

interface B extends A{
   public void print(String str);
   
   public void prinv(String str);
}
class C implements B{

   @Override
   public void print(String str) {
      // TODO Auto-generated method stub
      
   }

   @Override
   public void print() {
   }

   @Override
   public void printf() {
      // TODO Auto-generated method stub
      
   }

   @Override
   public void printr() {
      // TODO Auto-generated method stub
      
   }

   @Override
   public void prinv(String str) {
      // TODO Auto-generated method stub
      
   }



}


public class InterfaceDemo01 {
   public static void main(String[] args) {
      
   }
}

阅读全文 »

JAVA基础 27.Abstract

发表日期:2022-08-05 16:37:28 | 来源: | 分类:JAVA基础

      示例1
abstract class A{
   //1.抽象类中可以没有抽象方法(无意义,但是抽象方法必须没有方法体
   //2.抽象类中可以有(非抽象方法)被实现的方法即有方法体
   //3.抽象类中的所有抽象方法必须要被继承的 【非抽象子类】复写并实现,如果是抽象的子类则无需
   //4.抽象类不能被直接实例化

   public abstract void print(String str);
   
   public abstract void printf(String str);
   
   public void printr(String str){
      System.out.println(str);
   }
}

abstract class B extends A{

   @Override
   public void print(String str) {
      // TODO Auto-generated method stub
      System.out.println(str);
   }

   
}

class C extends B{

   @Override
   public void printf(String str) {
      // TODO Auto-generated method stub
      System.out.println(str);
   }
   
}


public class AbstractDemo01 {
   
   public static void main(String[] args) {
      
      A a = new C();
      a.printr("printr");
      a.print("print");
      a.printf("printf");
      
   }
}

阅读全文 »

JAVA基础 26.Iterator

发表日期:2022-08-05 16:36:39 | 来源: | 分类:JAVA基础

      示例1
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorDemo {

   public static void main(String[] args) {
      // TODO 自动生成的方法存根
      List<String> list = new ArrayList<String>();
      list.add("hello");
      list.add(",");
      list.add("world");

      Iterator<String> iterator = list.iterator();
      while (iterator.hasNext()) {

         System.out.print(iterator.next());

      }

   }

}

阅读全文 »

JAVA基础 24.Collection

发表日期:2022-08-05 16:35:35 | 来源: | 分类:JAVA基础

      示例1
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


public class ListDemo {

   /**
    * @param args
    */
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      Collection<String> collection = new ArrayList<String>();
      collection.add("eniac");
      collection.add("bast man!");
      
      List<String> list = new ArrayList<String>();
      list.add("hello");
      list.add("world");
      list.add(1,"-");
      list.addAll(0,collection);
      System.out.println(list);//[eniac, bast man!, hello, -, world]

      list.remove(3);
      System.out.println(list);//[eniac, bast man!, hello, world]
      for (int i = 0; i < list.size(); i++) {
         System.out.print(list.get(i));
      }

      System.out.println();
      System.out.println(list.toArray());//[Ljava.lang.Object;@c17164
      System.out.println(list.toArray(new String[]{}));//[Ljava.lang.String;@de6ced

   }

}

阅读全文 »

JAVA基础 23.Enumeration

发表日期:2022-08-05 16:34:47 | 来源: | 分类:JAVA基础

      示例1
import java.util.Enumeration;
import java.util.Vector;


public class EnumDemo01 {

   /**
    * @param args
    */
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      
      Vector<String> all = new Vector<String>();
      all.add("Hello ");
      all.add("world ");
      all.add("!");
      
      Enumeration<String> enumeration = all.elements();
      while (enumeration.hasMoreElements()) {
         String string = (String) enumeration.nextElement();
         System.out.print(string);
      }
      
      System.out.println("");
      
      //foreach 用PHP的习惯去解释 for(TYPE $val : $arr){}
      for (String string : all) {
         System.out.print(string);
      }
   }

}

阅读全文 »

JAVA基础 22.Properties

发表日期:2022-08-05 16:34:13 | 来源: | 分类:JAVA基础

      示例1
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 java.util.Properties;

public class PropertiesDemo01 {

   /**
    * @param args
    * @throws IOException 
    */
   
   public static void main(String[] args) throws IOException {
      // TODO Auto-generated method stub

      File file = new File("D:"+File.separator+"javaDemo.txt");
      
      Properties pro = new Properties();
      
      pro.setProperty("name", "张三");
      pro.setProperty("age", "22");
      pro.setProperty("sex", "男");
      
      System.out.println(pro.getProperty("name"));
      System.out.println(pro.getProperty("age"));
      System.out.println(pro.getProperty("sex"));
      
      //#保存至文件
      OutputStream out = new FileOutputStream(file);
      //pro.save(out , "这里是注释");//save方法过时了
      //pro.store(out, "这里是注释");
      //pro.storeToXML(out, "这里是注释", "GBK");
      pro.storeToXML(out, "这里是注释");//encoding 默认是UTF-8
      
      //#从文件中读取
      InputStream in = new FileInputStream(file);
      pro.loadFromXML(in);
      System.out.println(pro.getProperty("name"));
      System.out.println(pro.getProperty("age"));
      System.out.println(pro.getProperty("sex"));
   }

}

阅读全文 »

全部博文(1589)
集速网 copyRight © 2015-2025 宁ICP备15000399号-1 宁公网安备 64010402001209号
与其临渊羡鱼,不如退而结网
欢迎转载、分享、引用、推荐、收藏。