[个人总结]-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.自定义加密解密

import java.math.BigInteger;

public class MDUtil {

    //加密:转为16进制
    public static String encrypt(String plaintext){
        byte[] bytes = plaintext.getBytes();
        BigInteger bigInteger = new BigInteger(1, bytes);
        String hexString = bigInteger.toString(16);
        return hexString;
    }


    //解密:16进制转为字符串
    public static String decrypt(String hexStrings) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < hexStrings.length(); i+=2) {
            String hexDigit = hexStrings.substring(i, i + 2);
            int decimal = Integer.parseInt(hexDigit, 16);
            result.append((char) decimal);
        }
        return result.toString();
    }



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

13.dom4j读取xml文件

从xml文件中读取变量, 增加了读取流处理 使用SAXReader的read(File file)方法时,如果xml文件异常会导致文件被服务器占用不能移动文件,建议不使用read(File
* file)方法而使用read(FileInputStream fis)等流的方式读取文件,
* 异常时关闭流,这样就不会造成流未关闭,文件被锁的现象了。(在服务器中运行时会锁住文件,main方法却不会)。

   String configPath = "D:\\cmc_upload_download\\" + versionNumber + "\\BiddingDoc\\config\\base_package_config\\package_define.xml";
		
        FileInputStream fileInputStream = null;
        try {
            //判断是否有package_define.xml文件
            if (!new File(configPath).exists()) {
                JOptionPane.showMessageDialog(this, "请检查文件是否下载成功! " + versionNumber + " 可能为空包!", "提示", JOptionPane.DEFAULT_OPTION);
                return;
            }
            fileInputStream = new FileInputStream(configPath);
        } catch (FileNotFoundException e1) {
            // TODO 自动生成的 catch 块
            e1.printStackTrace();
        }

        SAXReader saxReader = new SAXReader();
        try {
            Document read = saxReader.read(fileInputStream);	//用FileInputStream类读取,避免xml文件占用
            Element rootElement = read.getRootElement();    //build_desc标签

            packageNname = rootElement.attributeValue("package_name");
            textArea4.setText(packageNname);

            configRepositoryValue = rootElement.attributeValue("config_repository");
            configBranchValue = rootElement.attributeValue("config_branch");
//            System.out.println(configRepositoryValue+"\n"+configBranchValue);
            textField4.setText(configRepositoryValue);
            textField5.setText(configBranchValue);


            //版本管控获取
            String versionControlRepository = rootElement.element("input").element("tools").element("package_res").element("repository").getText();
            textField1.setText(versionControlRepository);

            String versionControlBranch = rootElement.element("input").element("tools").element("package_res").element("branch").getText();
            textField2.setText(versionControlBranch);

            String versionControlTag = rootElement.element("input").element("tools").element("package_res").element("tag").getText();
            textField3.setText(versionControlTag);


        } catch (
                DocumentException e1) {
            // TODO 自动生成的 catch 块
            e1.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

14.xml文件解析

   String configPath = "D:\\cmc_upload_download\\" + versionNumber + "\\BiddingDoc\\config\\base_package_config\\package_define.xml";
		
        FileInputStream fileInputStream = null;
        try {
            //判断是否有package_define.xml文件
            if (!new File(configPath).exists()) {
                JOptionPane.showMessageDialog(this, "请检查文件是否下载成功! " + versionNumber + " 可能为空包!", "提示", JOptionPane.DEFAULT_OPTION);
                return;
            }
            fileInputStream = new FileInputStream(configPath);
        } catch (FileNotFoundException e1) {
            // TODO 自动生成的 catch 块
            e1.printStackTrace();
        }

        SAXReader saxReader = new SAXReader();
        try {
            Document read = saxReader.read(fileInputStream);	//用FileInputStream类读取,避免xml文件占用
            Element rootElement = read.getRootElement();    //build_desc标签

            packageNname = rootElement.attributeValue("package_name");
            textArea4.setText(packageNname);

            configRepositoryValue = rootElement.attributeValue("config_repository");
            configBranchValue = rootElement.attributeValue("config_branch");
//            System.out.println(configRepositoryValue+"\n"+configBranchValue);
            textField4.setText(configRepositoryValue);
            textField5.setText(configBranchValue);


            //版本管控获取
            String versionControlRepository = rootElement.element("input").element("tools").element("package_res").element("repository").getText();
            textField1.setText(versionControlRepository);

            String versionControlBranch = rootElement.element("input").element("tools").element("package_res").element("branch").getText();
            textField2.setText(versionControlBranch);

            String versionControlTag = rootElement.element("input").element("tools").element("package_res").element("tag").getText();
            textField3.setText(versionControlTag);


        } catch (
                DocumentException e1) {
            // TODO 自动生成的 catch 块
            e1.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

15.解决java执行exec阻塞

问题说明:
java后端执行cmd命令,windows上命令行能够成功,但是java使用exec执行,大部分时间都卡顿,无法执行完,也不报错。

二、阻塞原因
Java执行Runtime.getRuntime().exec()时,JVM会创建一个新的子进程去调用cmd窗口命令,同时该子进程与JVM建立三个连接管道:标准输入流(getInputStream)、标准输出流(getOutputStream)、标准错误流(getErrorStream)。
执行的cmd命令是对rtsp视频流截图,因为并没有参数的输入和得到结果,所以以为没有必要连同管道,虽然cmd窗口能够成功运行,但是运行的过程中会产生警告信息,因此得到的错误流迟迟得不到接受,就进行卡顿。

三、解决方法
主程序中执行命令,对错误流进行记录

 try {
            Process process4 = Runtime.getRuntime().exec(com);
            StreamGobbler errorGobbler = new StreamGobbler(process4.getErrorStream(),"ERROR");
            errorGobbler.start();
            StreamGobbler outGobbler = new StreamGobbler(process4.getInputStream(), "STDOUT");
            outGobbler.start();
            int proc = process4.waitFor();
//            当前线程等待,如果成功返回0,
            if(proc==0){
                System.out.println("成功");
            }else {
                System.out.println("失败");
            }
            if(process4!=null){
                process4.destroy();
            }
        }catch (IOException | InterruptedException e){
            e.printStackTrace();
        }


引入StreamGobbler类

package aiconnect;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
/**
 * 用于处理Runtime.getRuntime().exec产生的错误流及输出流
 *
 */
public class StreamGobbler extends Thread {
    InputStream is;
    String type;
    OutputStream os;

    public StreamGobbler(InputStream is, String type) {
        this(is, type, null);
    }

    StreamGobbler(InputStream is, String type, OutputStream redirect) {
        this.is = is;
        this.type = type;
        this.os = redirect;
    }
    public void run() {
        InputStreamReader isr = null;
        BufferedReader br = null;
//        pw用来创建一个文件,并向该文件中写入数据
        PrintWriter pw = null;
        try {
            if (os != null)
                pw = new PrintWriter(os);

            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null) {
                if (pw != null)
                    pw.println(line);
//                System.out.println(type + ">" + line);
            }

//            if (pw != null)
//                pw.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally{
//            pw.close();
            try {
                br.close();
                isr.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

16.HttpURLConnectionHelper

package utils;

import com.sun.javafx.logging.Logger;
import com.sun.org.apache.bcel.internal.generic.RETURN;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpRetryException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpURLConnectionHelper{
    public static String sendRequest(String urlParam,String requestType){
        HttpURLConnection con=null;
        BufferedReader buffer =null;
        StringBuffer resultBuffer=null;

        try {
            URL url = new URL(urlParam);
            con=(HttpURLConnection)url.openConnection();
            System.out.println(con);
            con.setRequestMethod(requestType);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            int responseCode = con.getResponseCode();
            if(responseCode ==HttpURLConnection.HTTP_OK){
                InputStream inputStream = con.getInputStream();
                resultBuffer = new StringBuffer();
                String line ;
                buffer=new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
                while((line= buffer.readLine())!=null){
                    resultBuffer.append(line);
                }
//                System.out.println(resultBuffer.toString());
                return  resultBuffer.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

17.Swing进度条

import com.sun.scenario.effect.impl.sw.java.JSWBlend_SRC_OUTPeer;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
 * Created by JFormDesigner on Wed Oct 18 09:41:23 CST 2023
 */

/**
 * @author 
 */
public class DownloadProgress {
    public DownloadProgress() {
        initComponents();
    }

    private void buttonExitDownloadMouseClicked(MouseEvent e) {
        // TODO add your code here
        //取消下载按钮
        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()+"  已中断");
                }
            }
        }
    }

    private void downloadProgresWindowClosed(WindowEvent e) {
        // TODO add your code here
        //下载窗口关闭时结束下载
        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()){
                    try {
                        threads[j].interrupt();
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
//                    System.exit(0);
                    System.out.println("线程-"+threads[j].getName()+"  已中断");
                }
            }
        }
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        downloadProgres = new JFrame();
        progressBar1 = new JProgressBar();
        label1 = new JLabel();
        buttonExitDownload = new JButton();
        panel1 = new JPanel();
        labelShowDownInfo = new JLabel();

        //======== downloadProgres ========
        {
            downloadProgres.setTitle("\u8fdb\u5ea6...");
            downloadProgres.setResizable(false);
            downloadProgres.setVisible(true);
            downloadProgres.setBackground(Color.white);
            downloadProgres.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            downloadProgres.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosed(WindowEvent e) {
                    downloadProgresWindowClosed(e);
                }
            });
            Container downloadProgresContentPane = downloadProgres.getContentPane();
            downloadProgresContentPane.setLayout(null);

            //---- progressBar1 ----
            progressBar1.setIndeterminate(true);
            progressBar1.setStringPainted(true);
            progressBar1.setString("  ");
            downloadProgresContentPane.add(progressBar1);
            progressBar1.setBounds(105, 55, 265, 40);

            //---- label1 ----
            label1.setIcon(new ImageIcon(getClass().getResource("/prompt.png")));
            downloadProgresContentPane.add(label1);
            label1.setBounds(40, 50, 40, 45);

            //---- buttonExitDownload ----
            buttonExitDownload.setText("\u53d6\u6d88");
            buttonExitDownload.setBackground(new Color(0xcccccc));
            buttonExitDownload.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    buttonExitDownloadMouseClicked(e);
                }
            });
            downloadProgresContentPane.add(buttonExitDownload);
            buttonExitDownload.setBounds(190, 115, 85, 35);

            //======== panel1 ========
            {
                panel1.setBackground(Color.white);
                panel1.setLayout(null);

                //---- labelShowDownInfo ----
                labelShowDownInfo.setBorder(null);
                panel1.add(labelShowDownInfo);
                labelShowDownInfo.setBounds(105, 20, 265, 30);

                {
                    // compute preferred size
                    Dimension preferredSize = new Dimension();
                    for(int i = 0; i < panel1.getComponentCount(); i++) {
                        Rectangle bounds = panel1.getComponent(i).getBounds();
                        preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                        preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
                    }
                    Insets insets = panel1.getInsets();
                    preferredSize.width += insets.right;
                    preferredSize.height += insets.bottom;
                    panel1.setMinimumSize(preferredSize);
                    panel1.setPreferredSize(preferredSize);
                }
            }
            downloadProgresContentPane.add(panel1);
            panel1.setBounds(0, 0, 445, 170);

            {
                // compute preferred size
                Dimension preferredSize = new Dimension();
                for(int i = 0; i < downloadProgresContentPane.getComponentCount(); i++) {
                    Rectangle bounds = downloadProgresContentPane.getComponent(i).getBounds();
                    preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                    preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
                }
                Insets insets = downloadProgresContentPane.getInsets();
                preferredSize.width += insets.right;
                preferredSize.height += insets.bottom;
                downloadProgresContentPane.setMinimumSize(preferredSize);
                downloadProgresContentPane.setPreferredSize(preferredSize);
            }
            downloadProgres.pack();
            downloadProgres.setLocationRelativeTo(downloadProgres.getOwner());
        }
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JFrame downloadProgres;
    private JProgressBar progressBar1;
    private JLabel label1;
    private JButton buttonExitDownload;
    private JPanel panel1;
    private JLabel labelShowDownInfo;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on


    public JProgressBar getProgressBar1() {
        return progressBar1;
    }


    public void setProgressBar1(JProgressBar progressBar1) {
        this.progressBar1 = progressBar1;
    }
}

18.文件权限

package com.example;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.HashSet;
import java.util.Set;

/**
* @Auther lmy
* @date 2024-06-26 22:53
* @Description This is description of code
*/
public class TestFile {
public static void main(String[] args) {
//判断文件夹写入权限
System.out.println(Files.isWritable(Paths.get("D:\\Tools")));

//判断文件/文件夹是否可读
System.out.println(Files.isReadable(Paths.get("D:\\a.txt")));
System.out.println(Files.isReadable(Paths.get("D:\\Tools")));

//判断文件/文件夹可执行权限
System.out.println(Files.isExecutable(Paths.get("D:\\a.txt")));
System.out.println(Files.isExecutable(Paths.get("D:\\Tools")));

try {
String command1="cmd /c echo y|cacls "+new File("C:\\Users\\xzq\\Desktop\\test\\FileAES.java").getCanonicalPath()+" /g everyone:r";

// 如果不加/e 会将写的权限代替command1中的读的权限 加了/e 会在原有权限基础上新增权限
String command2="cmd /c echo y|cacls "+new File("C:\\Users\\xzq\\Desktop\\test\\FileAES.java").getCanonicalPath()+"/e /g everyone:w";

String command3="cmd /c echo y|cacls "+new File("C:\\Users\\xzq\\Desktop\\test\\FileAES.java").getCanonicalPath()+"/e /g everyone:x";


// Runtime.getRuntime().exec(command1);
// Runtime.getRuntime().exec(command2);
// Runtime.getRuntime().exec(command3);
// System.out.println("命令执行完毕");


File file = new File("C:\\Users\\xzq\\Desktop\\111\\1.txt");
// 获取文件的权限集合
Set<PosixFilePermission> permissions = new HashSet<>(Files.getPosixFilePermissions(file.toPath()));

// 设置只读属性
permissions.add(PosixFilePermission.OWNER_READ);
permissions.add(PosixFilePermission.GROUP_READ);
permissions.add(PosixFilePermission.OTHERS_READ);

// 将设置后的权限应用到文件
Path path = file.toPath();
FileAttribute<Set<PosixFilePermission>> attribute = PosixFilePermissions.asFileAttribute(permissions);
try {
Files.setPosixFilePermissions(path, permissions);
System.out.println("文件只读属性设置成功!");
} catch (Exception e) {
System.out.println("文件只读属性设置失败:" + e.getMessage());
}

} catch (IOException e) {
throw new RuntimeException(e);
}








//
//
// Path filePath = Paths.get("C:\\Users\\xzq\\Desktop\\111\\1.txt"); // 替换为你的文件路径
//
// try {
// // 设置只读权限
// Set<PosixFilePermission> perms = PosixFilePermissions.fromString("r--r--r--");
// Files.setPosixFilePermissions(filePath, perms);
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// }








}

19.uuid(通用唯一识别码)

Java.Util包

uuid(通用唯一识别码)

String newFileName = UUID.randomUUID().toString() ;

结果实例:

9544c234-f477-4143-a3f8-d551c614e296
400cf69d-9989-466a-87fe-d91c7d338e83

20.修改文件中指定行文件

    /**
     * 修改文件指定行
     *
     * @param modifyFile    要修改的文件
     * @param lineNum       要修改的行号
     * @param replaceString 指定行替换后的字符串
     */
    public static void modifyline(File modifyFile, int lineNum, String replaceString) {
        boolean exists = modifyFile.exists();

        String modifyFileName = modifyFile.getName();
        if (!exists) {
            throw new FileNotFoundExection(MessageConstant.FILE_NOT_FOUND);
        } else {
            FileReader fileReader = null;
            BufferedReader in = null;
            FileWriter fileWriter = null;
            BufferedWriter bufferedWriter = null;
            PrintWriter out = null;

            try {
                fileReader = new FileReader(modifyFile);
                in = new BufferedReader(fileReader);


                fileWriter = new FileWriter(System.getProperty("user.dir") + "\\" + modifyFileName + "_tmp.tmp");

                bufferedWriter = new BufferedWriter(fileWriter);
                out = new PrintWriter(bufferedWriter);
                String line;
                int count = 1;
                while ((line = in.readLine()) != null) {
                    if (count == lineNum) {
                        out.println(line.replace(line, replaceString));
                    } else {
                        out.println(line);
                    }
                    count++;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    assert out != null;
                    out.close();
                    bufferedWriter.close();
                    fileWriter.close();
                    in.close();
                    fileReader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                boolean delete = modifyFile.delete();
                if (delete) {
                    File file1 = new File(System.getProperty("user.dir") + "\\" + modifyFileName + "_tmp.tmp");
                    boolean b = file1.renameTo(modifyFile);
                    if (b) {
                        log.info(file1.getAbsolutePath() + " 已重命名为 " + modifyFile.getAbsolutePath());
                    }
                } else {
                    log.error(modifyFile.getAbsolutePath() + " 删除失败");
                }
            }

        }
    }

21.fastjson

package com.example.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.Arrays;

public class JsonFormat {

    public static String format(String jsonStr) {
        // 解析时保持顺序
        JSONObject jsonObject = JSON.parseObject(jsonStr, Feature.OrderedField);

        // 格式化输出(保持顺序并美化)
        String formattedJsonStr = JSON.toJSONString(jsonObject,
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.QuoteFieldNames);

        return formattedJsonStr;
    }
}

22.ssh连接远程服务器操作

package com.example.linuxServer.ConnectServerExecuteCommand;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

@Slf4j
public class SSHConnect {

    /**
     * ssh连接服务器
     *
     * @param serverInfo
     * @return
     */
    public static Session connectLinux(ServerInfo serverInfo) {
        Session session = null;
        try {
            // 1. 创建JSch会话
            JSch jsch = new JSch();
            session = jsch.getSession(serverInfo.getSshUser(), serverInfo.getHost(), serverInfo.getPort());
            session.setPassword(serverInfo.getSshPassword());
            session.setConfig("StrictHostKeyChecking", "no");

            log.info("尝试连接到服务器: " + serverInfo.getSshUser() + "@" + serverInfo.getHost());
            session.connect(30000); // 设置超时时间为 30 秒
            log.info("连接成功");

        } catch (JSchException e) {
            log.info("连接失败: " + e.getMessage());
            e.printStackTrace();
        }
        return session;
    }


    /**
     * ssh连接上后执行linux命令
     *
     * @param command
     * @return
     * @throws Exception
     */
    public static void executeCommand(String command, Session session) {
       
        if (session == null) {
            throw new RuntimeException("session is null,可能已断开连接...");

        } else {
            ChannelExec channel = null;
            StringBuilder output = new StringBuilder();

            try {
                channel = (ChannelExec) session.openChannel("exec");
                channel.setCommand(command);

                // 获取输入流
                InputStream in = channel.getInputStream();
                InputStream err = channel.getErrStream();

                // 异步读取错误流
                Thread errorThread = new Thread(() -> readStream(err, output, "[ERROR] "));
                errorThread.start();

                channel.connect();

                // 读取标准输出
                readStream(in, output, "");

                // 等待执行完成
                while (!channel.isClosed()) {
                    Thread.sleep(100);
                }

                errorThread.join();  // 等待错误流读取完成

                // 检查退出状态
                if (channel.getExitStatus() != 0) {
                    output.append("\nExit Code: ").append(channel.getExitStatus());
                }
                log.info(output.toString());

            } catch (JSchException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }

    }


    /**
     * 通用流读取方法:读命令结果
     *
     * @param stream
     * @param output
     * @param prefix
     */
    private static void readStream(InputStream stream, StringBuilder output, String prefix) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(prefix).append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 判断远程服务器文件是否存在
     *
     * @param remoteFilePath 远程服务器文件路径
     * @param session
     * @return
     */
    public static boolean fileIsExist(String remoteFilePath, Session session) {
        ChannelSftp sftpChannel = null;
        try {
            // 创建SFTP通道
            Channel channel = session.openChannel("sftp");
            channel.connect();
            sftpChannel = (ChannelSftp) channel;

            // 3. 检查文件是否存在
            sftpChannel.lstat(remoteFilePath); // 尝试获取文件属性
            return true; // 无异常则文件存在
        } catch (SftpException e) {
            if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
                return false; // 文件不存在
            }
            throw new RuntimeException("SFTP错误: " + e.getMessage(), e);
        } catch (JSchException e) {
            throw new RuntimeException("连接失败: " + e.getMessage(), e);
        } finally {
            if (sftpChannel != null) sftpChannel.disconnect();
        }
    }


    /**
     * 使用 JSch 库通过SFTP传输文件(无需依赖外部工具)
     *
     * @param session    远程服务器session
     * @param localFile  本地文件路径
     * @param remoteFile 远程目标目录
     * @return
     */
    public static boolean SftpTransfer(Session session, String localFile, String remoteFile) {
        try {
            ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");
            sftp.connect();
            sftp.put(localFile, remoteFile);

            sftp.disconnect();
            return true;
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 本地SCP命令+sshpass	代码简单,直接复用系统工具	密码明文不安全,依赖外部环境
     *
     * @param host      远程服务器IP
     * @param port      端口
     * @param user      用户名
     * @param password  密码
     * @param localFile 本地文件路径
     * @param remoteDir 远程目标目录
     * @return
     */
    public static boolean transferFileWithScp(
            String host, int port, String user, String password,
            String localFile, String remoteDir) {

        // 构建SCP命令(使用sshpass传递密码)
        String scpCommand = String.format(
                "sshpass -p '%s' scp -P %d -o StrictHostKeyChecking=no %s %s@%s:%s",
                password, port, localFile, user, host, remoteDir
        );

        try {
            // 执行命令
            Process process = Runtime.getRuntime().exec(new String[]{"bash", "-c", scpCommand});

            // 读取命令输出和错误流
            readStream(process.getInputStream());
            readStream(process.getErrorStream());

            // 等待命令执行完成
            int exitCode = process.waitFor();
            return exitCode == 0;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }





    // 读取输入流内容(用于调试)
    private static void readStream(InputStream inputStream) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }


    /**
     * 断开ssh连接
     *
     * @param session
     */
    public static void disconnect(Session session) {
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
    }
}

测试:

package com.example;

import com.example.linuxServer.ConnectServerExecuteCommand.SSHConnect;
import com.example.linuxServer.ConnectServerExecuteCommand.ServerInfo;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.example.ReadFileUtil;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
public class TestMain {


    public static void main(String[] args) throws Exception {
        log.info("参数输出:");
        String icap_branch = args[0];
        log.info(icap_branch);

        String deploy_time = args[1];
        log.info(deploy_time);

//       log.info("====================获取list.txt====================");
        File listFile = new File("/root/.jenkins/workspace/testFreeStyle/list.txt");
        boolean listexists = listFile.exists();
        if (listexists) {
            log.info("list.txt已获取");
        } else {
//           log.info("/root/.jenkins/workspace/testFreeStyle/list.txt不存在");
            return;
        }
//       log.info("====================结束获取list.txt====================");
//       log.info("==================== 解析list.txt  ====================");
        String[] strings = ReadFileUtil.readLine("/root/.jenkins/workspace/testFreeStyle/list.txt");

        //判断代码文件格式类型个数
        Map<String, Integer> formatTypeMap = new HashMap<>();

        //list.txt里的文件
        List<String> lists = new ArrayList<>();
        for (String string : strings) {
            String trim = string.trim();
            lists.add(trim);
            String type = trim.substring(trim.lastIndexOf(".") + 1, trim.length());
//            System.out.println(type);
//           log.info("============ 清单列表  ============");
            log.info(trim);
            if (!formatTypeMap.containsKey(type)) {
                formatTypeMap.put(type, 1);
            } else {
                formatTypeMap.put(type, formatTypeMap.get(type) + 1);
            }
        }

        //输出文件清单个数
        log.info("list.txt清单个数统计: ");
        for (String types : formatTypeMap.keySet()) {
            log.info(types + ": " + formatTypeMap.get(types) + " 个");
        }


//       log.info("============ 清单列表  ============");
        ServerInfo serverInfo = ServerInfo.builder()
                .host("192.168.206.137")
                .port(22)
                .sshUser("root")
                .sshPassword("root")
                .build();
        Session session = SSHConnect.connectLinux(serverInfo);
        log.info(session.toString());
        if (session.isConnected()) {
            log.info("连接成功");
        }
//        log.info("pwd: " + SSHConnect.executeCommond("pwd", session));


        SSHConnect.executeCommand("pwd", session);


        //备份服务器代码
        log.info("开始备份服务器代码...");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = simpleDateFormat.format(new Date());
        String backupCommand = "tar -cvf /root/mbank_jl_backup/mbank-jl_" + dateString + ".tar icap-mbank-jl";
        log.info(backupCommand);
//        System.out.println(session);
        SSHConnect.executeCommand(backupCommand, session);
        String backupFile = "/root/mbank_jl_backup/mbank-jl_" + dateString + ".tar";
        Thread.sleep(2000);

        //判断远程服务器文件是否存在
        if (SSHConnect.fileIsExist(backupFile, session)) {
            log.info("已备份代码,路径:" + backupFile);
        }

        log.info("==================== 开始部署   ====================");

        for (String list : lists) {
            //清单里代码文件的类型
            String type = list.substring(list.lastIndexOf(".") + 1, list.length());
            if ("java".equals(type)) {
                //抽class
                //编译后class代码的路径:/root/.jenkins/workspace/testFreeStyle/icap_mbank_jl/target/classes
               /* SSHConnect.transferFileWithScp(serverInfo.getHost(),serverInfo.getPort(),serverInfo.getSshUser(),serverInfo.getSshPassword(),
                        "/.jenkins/workspace/testFreeStyle/icap_mbank_jl/target/classes/com/example/demoapplication/result/PageResult.class",
                        "/root/icap-mbank-jl/DemoApplication/src/main/java/com/example/demoapplication/result/");*/

               /* SSHConnect.executeCommand("sshpass -p \"root\" " +
                        "scp -o StrictHostKeyChecking=no " +
                        "root@192.168.206.136:/.jenkins/workspace/testFreeStyle/icap_mbank_jl/target/classes/com/example/demoapplication/result/PageResult.class  " +
                        "/root/icap-mbank-jl/DemoApplication/src/main/java/com/example/demoapplication/result/", session);*/
            }

            boolean transferResult = SSHConnect.SftpTransfer(session,
                    "/root/.jenkins/workspace/testFreeStyle/icap_mbank_jl/target/classes/com/example/demoapplication/result/PageResult.class",
                    "/root/icap-mbank-jl/DemoApplication/src/main/java/com/example/demoapplication/result/");
            if (transferResult) {
                log.info("/com/example/demoapplication/result/PageResult.class  复制成功");
            } else {
                log.error("/com/example/demoapplication/result/PageResult.class  复制失败");
            }
            if ("".equals(type)) {

            }
        }
        log.info("==================== 结束部署   ====================");
        SSHConnect.disconnect(session);


        Thread.sleep(4000);
        log.info("休眠4秒");
        log.info("程序退出");
        System.exit(0);

    }
}

23.指定格式获取当前系统时间

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = simpleDateFormat.format(new Date());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值