用Java写脚本,常用的一些方法

用Java写脚本,常用的一些方法

平时用的一些小方法,总结之

1.运行一个可执行程序

比如,你如果想运行如下命令

C://test//aapt.exe -f params1 -M params2

try {
        ProcessBuilder pb = new ProcessBuilder("C://test//aapt.exe","-f","params1","-M","params2");
        pb.redirectErrorStream(true);
        Process process = pb.start();
        InputStream inputStream = process.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream));
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(INFO + line);
        }
        int exit = process.waitFor();
        if (exit == 0) {
            System.out.println("finished...");
        } else {
            System.out.println("error...");
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }


注意:
1.调用ProcessBuilder的start()方法,开始执行命令。
2.通过process.getInputStream,把执行命令过程中的日志打印出来。
3.通过调用process.waitFor(),阻塞当前线程,直到命令执行完毕后,获得返回码

2.获取当前Class在运行时的路径(亦适用于jar)

比如,获取TestMain这个类在运行时的路径。

URL location = TestMain.class.getProtectionDomain().getCodeSource()
            .getLocation();
String path = location.getFile();

3.获取系统的环境变量

比如,获取系统的JAVA_HOME这个环境变量的值

String path = System.getenv("JAVA_HOME");

4.删除目录

public static boolean deleteDirectory(File directory) {
    if (directory.exists()) {
        File[] files = directory.listFiles();
        if (null != files) {
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                } else {
                    files[i].delete();
                }
            }
        }
    }
    return (directory.delete());
}

5.读写文件

/**
 * 写文件
 *
 * @param filePath
 * @param sets
 * @throws IOException
 */
public synchronized void writeFile(String filePath, String content)
        throws IOException {
    FileWriter fw = new FileWriter(filePath);
    PrintWriter out = new PrintWriter(fw);
    out.write(content);
    out.println();
    fw.close();
    out.close();
}

/**
 * 读文件
 *
 * @param filename
 * @return
 */
public static String readFile(String filepath) {
    File file = new File(filepath);
    InputStream inputStream = null;
    BufferedReader bufferedReader = null;
    try {
        inputStream = new FileInputStream(file);
        String content = "";
        if (inputStream != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(
                    inputStream));
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                content += line;
            }
        }
        return content;
    } catch (Exception e) {
        System.out.println(e.toString());
    } finally {
        try {
            if (bufferedReader != null) {
                bufferedReader.close();
                bufferedReader = null;
            }
            if (inputStream != null) {
                inputStream.close();
                inputStream = null;
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }

    return null;
}

public static byte[] readByte(final InputStream in) throws IOException {
    ByteArrayOutputStream output = null;
    try {
        if (in == null) {
            return null;
        }
        output = new ByteArrayOutputStream(1024 * 2);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }
        return output.toByteArray();
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

public static boolean saveObject(Serializable serializable,
        String filePath) {
    try {
        FileOutputStream fout = new FileOutputStream(filePath);
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(serializable);
        oos.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

6.TODO

  • 12
    点赞
  • 69
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,下面是几个常用的 Linux 脚本,使用 Shell 编实现: 1. 自动备份脚本: ```bash #!/bin/bash # 备份目录 backup_dir=/path/to/backup # 数据库信息 db_host=localhost db_user=root db_password=123456 db_name=mydb # 备份文件名 backup_file=backup-$(date +%Y%m%d%H%M%S).tar.gz # 打包文件 tar -czf $backup_dir/$backup_file /path/to/backup # 备份数据库 mysqldump -h$db_host -u$db_user -p$db_password $db_name > $backup_dir/$db_name.sql # 打包数据库 tar -czf $backup_dir/$db_name-$(date +%Y%m%d%H%M%S).tar.gz $backup_dir/$db_name.sql # 上传备份文件 scp $backup_dir/$backup_file user@remote:/path/to/backup scp $backup_dir/$db_name-*.tar.gz user@remote:/path/to/backup # 清理备份文件 find $backup_dir -name "backup-*" -mtime +7 -exec rm {} \; find $backup_dir -name "$db_name-*.tar.gz" -mtime +7 -exec rm {} \; ``` 该脚本将指定目录和数据库备份到本地,并使用 scp 命令将备份文件上传到远程服务器。最后,使用 find 命令清理过期的备份文件。 2. 自动清理脚本: ```bash #!/bin/bash # 清理目录 clean_dir=/path/to/clean # 清理时间 clean_time=7 # 清理过期文件 find $clean_dir -type f -mtime +$clean_time -exec rm {} \; ``` 该脚本将指定目录中的过期文件清理掉,根据实际需要修改清理时间。 3. 自动部署脚本: ```bash #!/bin/bash # 代码仓库 [email protected]:username/repo.git # 代码目录 code_dir=/path/to/code # 构建命令 build_cmd="mvn clean package" # 服务器信息 server=user@server:/path/to/deploy # 拉取代码 git clone $code_repo $code_dir # 构建代码 cd $code_dir && $build_cmd # 上传代码 scp $code_dir/target/*.jar $server # 启动服务 ssh $server "nohup java -jar /path/to/deploy/*.jar > /dev/null 2>&1 &" ``` 该脚本使用 Git 拉取代码,使用 Maven 编译代码,并使用 scp 命令将编译后的代码上传到服务器。最后,使用 ssh 命令启动服务。 4. 自动监控脚本: ```bash #!/bin/bash # 联系人 [email protected] # 系统负载 load_avg=$(uptime | awk '{print $10}') # 进程状态 process_status=$(ps -ef | grep nginx | grep -v grep) # 网络连接 network_status=$(netstat -an | grep 80 | grep ESTABLISHED) # 发送邮件 if [ $(echo "$load_avg > 1.0" | bc) -eq 1 ] || [ -z "$process_status" ] || [ -z "$network_status" ]; then echo "Warning: system load is high or nginx process is not running or network connection is not established" | mail -s "Server Status Alert" $contact fi ``` 该脚本定期检查系统负载、进程状态和网络连接,并根据检查结果发送邮件报警。 以上是几个常用的 Linux 脚本,使用 Shell 编实现,可以根据实际需求修改脚本内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值