您的位置:首页 > 财经 > 产业 > [个人总结]-java常用方法

[个人总结]-java常用方法

2024/10/6 14:25:03 来源:https://blog.csdn.net/weixin_45210565/article/details/139382740  浏览:    关键词:[个人总结]-java常用方法

1.获取项目根路径

user.dir是一个系统属性,表示用户当前的工作目录,大多数情况下,用户的当前工作目录就是java项目的根目录(src文件的同级路径)

System.getProperty("user.dir")

结果:D:\code\idea\GetInfo

2.java中执行CMD命令

//创建目录结构/**目录结构:运行目录\包类型\pr_path\pr_label* */String property = System.getProperty("user.dir"); //当前工作目录,src文件的同级路径String dirString = property + "\\" + (prPath.replace("/", "\\")) + "\\" + prLabel;System.out.println("创建的目录结构: " + dirString);String createPrWorkspaceCommond = "mkdir " + dirString;try {Process process = Runtime.getRuntime().exec("cmd.exe /c " + createPrWorkspaceCommond + " >>p4Download.txt");try {int waitFor = process.waitFor(); //用于阻塞进程 下载完版本后才可进行后续操作} catch (InterruptedException e1) {e1.printStackTrace();}} catch (IOException e1) {e1.printStackTrace();}

3.获取线程

        //取消下载按钮downloadProgres.dispose();ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();int i = threadGroup.activeCount();Thread[] threads = new Thread[i];threadGroup.enumerate(threads);System.out.println("线程总个数:" + i);for (int j = 0; j < i; j++) {String name = threads[j].getName();System.out.println("第" + j + "个线程名为:" + name);if ("DownloadThread".equals(name)) {if (threads[j].isAlive()) {threads[j].interrupt();System.out.println("线程-" + threads[j].getName() + " 已中断");}}}

4.匿名内部类多线程动态更新swing窗口

new Thread(new Runnable() {
    @Override
    public void run() {
        downloadProgress.getProgressBar1().setString("");
    }
}).start();

5.java调用cmd执行命令

try {
    // 调用CMD命令
    String command = "ipconfig";
    Process process = Runtime.getRuntime().exec(command);
    // 获取命令输出结果
    InputStream inputStream = process.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GBK")); // 设置编码为GBK
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    // 等待命令执行完成
    process.waitFor();
} catch (IOException | InterruptedException e) {
    e.printStackTrace();
}

6.java调用cmd执行ipconfig命令

1.基础命令

cmd /c dir 是执行完dir命令后关闭命令窗口。

cmd /k dir 是执行完dir命令后不关闭命令窗口。

cmd /c start dir 会打开一个新窗口后执行dir指令,原窗口会关闭。

cmd /k start dir 会打开一个新窗口后执行dir指令,原窗口不会关闭

2.执行完毕后不关闭cmd页面

private static void cmdExec() {

try {

Runtime.getRuntime().exec("cmd /k start cmd.exe /k ipconfig");

} catch (Exception e) {

log.error(e.getMessage(), e);

}

}

7.MD5加密工具类
方式一:

package cn.tx.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密的工具类
 */
public class MD5Utils {

    /**
     * 使用md5的算法进行加密
     */
    public static String encrypt(String content) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(content.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法!");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
        // 如果生成数字未满32位,需要前面补0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    public static void main(String[] args) {
        System.out.println(encrypt("admin"));
    }

}

方式二:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
public class MD5Util {
 
    // 加密方法:接收一个字符串明文,返回使用 MD5 加密后的哈希值
    public static String encrypt(String plaintext) throws NoSuchAlgorithmException {
        // 使用 MD5 算法创建 MessageDigest 对象
        MessageDigest md = MessageDigest.getInstance("MD5");
        // 更新 MessageDigest 对象中的字节数据
        md.update(plaintext.getBytes());
        // 对更新后的数据计算哈希值,存储在 byte 数组中
        byte[] digest = md.digest();
        // 将 byte 数组转换为十六进制字符串
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b & 0xff));
        }
        // 返回十六进制字符串
        return sb.toString();
    }
 
    // 解密方法:接收一个字符串明文和一个使用 MD5 加密后的哈希值,返回解密结果(true 表示匹配,false 表示不匹配)
    public static boolean decrypt(String plaintext, String encrypted) throws NoSuchAlgorithmException {
        // 调用加密方法计算出明文的哈希值
        String decrypted = encrypt(plaintext);
        // 比较计算得到的哈希值和输入的哈希值是否相同
        return decrypted.equals(encrypted);
    }
}

8.管理权限运行命令

需要管理员权限执行的命令可以通过执行bat脚本

如:拷贝文件到C:\Windows\System32目录下需要管理员权限

获取管理员权限:

1、新建脚本,如copyFile.bat,内容如下

@echo off

chcp 65001
echo 正在复制文件到System32目录...
cd /d %~dp0
%1 start "" mshta vbscript:createobject("shell.application").shellexecute("""%~0""","::",,"runas",1)(window.close)&exit
copy /Y "D:\Code\swingTest\123shsghajw.exe" "%windir%\System32\"
echo 复制完成。
pause

注:

  • %windir%    表示windows系统文件的安装目录,即:C:\windows
  • 将以下代码放在要获取管理员权限执行的代码前
  • chcp 65001   更改编码为UTF-8

%1 start "" mshta vbscript:createobject("shell.application").shellexecute("""%~0""","::",,"runas",1)(window.close)&exit

2、java中使用exec执行脚本

Runtime.getRuntime().exec("cmd /c copyFile.bat",null,new File(System.getProperty("user.dir")));

注:user.dir是一个系统属性,表示用户当前的工作目录,大多数情况下,用户的当前工作目录就是java项目的根目录(src文件的同级路径)

9.java中指定字符串编码

new String("我喜欢java".getBytes(), StandardCharsets.UTF_8);

10.bat脚本中指定编码

chcp 936

936 代表的是GBK 编码,是专门针对中文的编码

11.Properties类读写文件

读文件

 File file = new File(System.getProperty("user.dir") + "\\my.properties");InputStream inputStream = null;if (file.exists()) {Properties properties = new Properties();try {inputStream = new FileInputStream(file);properties.load(inputStream);for (String propertyName : properties.stringPropertyNames()) {Object propertyValue = properties.get(propertyName);LOGGER.info("属性名:" + propertyName + " 属性值:" + propertyValue);if ("username".equals(propertyName)) {textFieldUsername.setText((String) propertyValue);}if ("password".equals(propertyName)) {passwordFieldPassword.setText((String) propertyValue);}}} catch (IOException e) {throw new RuntimeException(e);} finally {try {inputStream.close();} catch (IOException e) {throw new RuntimeException(e);}}}

写文件:

if (checkBox1.isSelected()) {String username = textFieldUsername.getText();String password = new String(passwordFieldPassword.getPassword());File file = new File(System.getProperty("user.dir") + "\\my.properties");if (!file.exists()) {try {boolean newFile = file.createNewFile();} catch (IOException ex) {throw new RuntimeException(ex);}}OutputStream outputStream = null;try {outputStream = new FileOutputStream(file);Properties properties = new Properties();properties.setProperty("username", username);properties.setProperty("password", password);properties.store(outputStream, "账号密码");} catch (IOException ex) {throw new RuntimeException(ex);} finally {try {outputStream.close();} catch (IOException ex) {throw new RuntimeException(ex);}}}

12.自定义加密解密

package com.example;/*** @Auther lmy* @date 2024-06-04 2:27* @Description This is description of code*/
public class MDUtil {//加密public static String encrypt(String plaintext) {String hexString = "";char[] charArray = plaintext.toCharArray();for (int i = 0; i < charArray.length; i++) {if(i==0){hexString = hexString + Integer.toHexString(charArray[i]);continue;}hexString = hexString + "-" + Integer.toHexString(charArray[i]);}return hexString;}public static String decrypt(String hexStrings) {String chars = "";for (String s : hexStrings.trim().split("-")) {char ch = (char) Integer.parseInt(s, 16);chars = chars + ch;}return chars;}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com