1. 程式人生 > >java執行命令和String輸出到文字

java執行命令和String輸出到文字

 

    //java中執行“命令”	
    private static String runCommand(String calarmServiceUrl) {
		StringBuffer output = new StringBuffer();
	    try {     
	        //Process process = Runtime.getRuntime().exec("curl -X GET http://calm.default.svc.cluster.local:8182/api/alma/alarms?sourceObject="+ParameterUitls.getSDN()+" | sed 's/@//g'");  
	    	//Process process = Runtime.getRuntime().exec("curl -X GET http://calm.default.svc.cluster.local:8182/api/alma/alarms | sed 's/@//g'");  
	        //Process process = Runtime.getRuntime().exec("curl -X GET "+calarmServiceUrl+"?sourceObject="+ParameterUitls.getSDN()+" | sed 's/@//g'");  
	        Process process = Runtime.getRuntime().exec("curl -X GET "+calarmServiceUrl+"?sourceObject="+ParameterUitls.getSDN());  
	        InputStream input = process.getInputStream();
	        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
	        String szline;
	        while ((szline = reader.readLine())!= null) {
	            output.append(szline + "\n");
	        }
	        
	        reader.close();
	        process.waitFor();
	        process.destroy();
	    } catch (Exception e) {  
	    	LOGGER.warn(e);
	        return null;
	    }
	    return output.toString().replace("@","");
	
	}

	//String輸出到alarm.json檔案
	public static void outFile(String s) {
		if(s!=null) {
			String path = AlarmManager.class.getResource("/").toString() + "alarm.json";
			if (path.contains(":")) {
				path = path.replace("file:/", "");
			}
			File file = new File(path);
			try (FileOutputStream fop = new FileOutputStream(file)) {
				// if file doesn't exists, then create it
				if (!file.exists()) {
					file.createNewFile();
				}
				// get the content in bytes
				byte[] contentInBytes = s.getBytes();
	
				fop.write(contentInBytes);
				fop.flush();
				fop.close();
				//System.out.println("Done");
			} catch (IOException e) {
				LOGGER.warn(e);
			}
		}else {
	    	LOGGER.warn("fail to output file ");
		}
	}