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

本文介绍了使用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

使用Java脚本有多种方式,以下为不同场景下的编方法及示例: ### 访问Java对象的脚本 可以将`java.io.File`对象作为全局变量,脚本可访问该变量并调用其公共方法。在JavaScript中支持“自然”的类似Java的语法。示例代码如下: ```java import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import java.io.File; public class JavaScriptWithJavaObject { public static void main(String[] args) { // 创建一个JavaScript脚本引擎 ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); // 创建一个File对象并将其作为全局变量 File file = new File("test.txt"); try { // 将File对象绑定到脚本引擎的全局变量中 engine.put("file", file); // 执行JavaScript脚本,调用File对象的公共方法 engine.eval("print(file.exists());"); } catch (ScriptException e) { e.printStackTrace(); } } } ``` ### 运行Shell脚本Java中运行shell脚本,可以使用`Runtime`类或者`ProcessBuilder`类。使用`Runtime.exec`方法的示例代码如下: ```java import java.io.BufferedReader; import java.io.InputStreamReader; public class RunShellScript { public static void main(String[] args) { try { // 假设你的shell脚本路径是 /path/to/your/script.sh String command = "/bin/bash /path/to/your/script.sh"; // 使用Runtime执行命令 Process process = Runtime.getRuntime().exec(command); // 读取脚本输出 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待脚本执行完成 process.waitFor(); // 获取退出值 int exitValue = process.exitValue(); System.out.println("Exit value: " + exitValue); } catch (Exception e) { e.printStackTrace(); } } } ``` ### 编Java运行脚本 运行Java程序的脚本示例如下: ```plaintext java -cp handeworkcheck.jar;./lib/activation-1.1.jar;./lib/apacheds-i18n-2.0.0-M15.jar;./lib/zkclient-0.8.jar;./lib/zookeeper-3.4.6.jar com.it18zhang.calllog.consumer.HbaseConsumer ``` 此脚本使用`java`命令,通过`-cp`指定类路径,然后指定要运行的主类。 ### 常用方法要点 编Java脚本时,常用的一些方法要点如下: 1. 调用`ProcessBuilder`的`start()`方法,开始执行命令。 2. 通过`process.getInputStream`,把执行命令过程中的日志打印出来。 3. 通过调用`process.waitFor()`,阻塞当前线程,直到命令执行完毕后,获得返回码。 示例代码如下: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ProcessBuilderExample { public static void main(String[] args) { try { // 创建ProcessBuilder对象并指定要执行的命令 ProcessBuilder processBuilder = new ProcessBuilder("ls", "-l"); // 启动进程 Process process = processBuilder.start(); // 读取命令执行的输出 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待命令执行完毕并获取返回码 int exitCode = process.waitFor(); System.out.println("Exit code: " + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值