package org.springblade.common.utils;

import cn.hutool.core.collection.CollUtil;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Author pangqijun
 * Date 2022/11/25
 * Description
 */
public class LinuxUtil {

	/**
	 * 运行Linux命令
	 * @author YuanRiKang
	 * @date 2022/5/24 16:56
	 * @param commands 命令集合
	 * @return 返回结果
	 */
	public static List<String> executeNewFlow(List<String> commands) {
		List<String> rspList = new ArrayList<>();
		Runtime run = Runtime.getRuntime();
		try {
			Process proc = run.exec("/bin/bash", null, null);
			BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
			for (String line : commands) {
				out.println(line);
			}
			out.println("exit");// 这个命令必须执行，否则in流不结束。
			String rspLine = "";
			while ((rspLine = in.readLine()) != null) {
				System.out.println(rspLine);
				rspList.add(rspLine);
			}
			proc.waitFor();
			in.close();
			out.close();
			proc.destroy();
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return rspList;
	}


	public static void main(String[] args) {
		List<String> commands = new ArrayList<>();
		commands.add("ls -lt --time-style=\"+%Y-%m-%d %H:%I:%S\" /Users/pangqijun/Downloads/store/apklog");
		List<String> strings = LinuxUtil.executeNewFlow(commands);
		strings.forEach(e -> {
			System.out.println(e);
			String[] s = e.split(" ");
			System.out.println(s[s.length - 1]);
		});
	}
}
