1.java调用cmd命令:
Runtime.getRuntime().exec("taskkill /f /im firefox.exe");
2.使用了loadProp()方法调用jar包内的properties文件
使用java程序监控geneFTP服务器(使用windows计划任务执行jar包),代码如下:(工程目录结构见附件)
Task.java:
package com.monitor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.ahcomic.framework.util.common.SendMail;
import com.ahcomic.framework.util.common.StringUtil;
import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPConnectMode;
import com.enterprisedt.net.ftp.FTPTransferType;
public class Task {
public static final String MAIL_SMTPSERVER = "mail.tora.to";
public static final String MAIL_USER = "torachan@tora.to";
public static final String MAIL_PASSWORD = "dimen29019853";
public static final String MAIL_FROM = "torachan@tora.to";
public static final String genehosts = loadProp("gene6.ftp.hosts");
public static final String geneports = loadProp("gene6.ftp.ports");
public static final String geneusers = loadProp("gene6.ftp.users");
public static final String genepwds = loadProp("gene6.ftp.pwds");
public static final String logPath = loadProp("gene6.log.path");
public static final String txtPaths = loadProp("gene6.test.txt.paths");
public static final String failcount = loadProp("schedule.fail.count");
public static final String sendemails = loadProp("schedule.send.emails");
private static final String taskkill = loadProp("schedule.taskkill.flag");
private static Map<String, Integer> map1 = new HashMap<String, Integer>();
private static Long now = System.currentTimeMillis();
public static void main(String[] args) {
System.out.println(taskkill);
if("1".equals(taskkill)){
try {
Runtime.getRuntime().exec("taskkill /f /im java.exe");
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
genesConn();
//System.out.println(loadProp("gene6.log.path"));
}
public static void genesConn() {
System.out.println("[" + getdateFmt(System.currentTimeMillis())
+ "] geneftp connection begin!");
String[] hosts = genehosts.split(",");
String[] ports = geneports.split(",");
String[] users = geneusers.split(",");
String[] pwds = genepwds.split(",");
String[] txts = txtPaths.split(",");
for (int i = 0; i < hosts.length; i++) {
if (!StringUtil.isBlank(hosts[i])) {
try {
testGene6(hosts[i], ports[i], users[i], pwds[i], txts[i]);
} catch (Exception e) {
continue;
} finally {
Map<String, Integer> map = readLog();
String host = hosts[i];
String txt = txts[i];
// check file
if (map.containsKey(host)) {
int count = map.get(host);
File file = new File(getTrueTxt(txt));
if (file.exists()) {
file.delete();
if(i==hosts.length-1){
delFold(txts[i]);
}
map1.put(host, 0);
} else {
if (count < Integer.valueOf(failcount)) {
map1.put(host, count + 1);
System.out
.println("["
+ getdateFmt(System
.currentTimeMillis())
+ "]监控到" + host + "的geneftp第"
+ Integer.valueOf(count + 1)
+ "次出错!");
} else {
String[] emails = sendemails.split(",");
for (String email : emails) {
if (!StringUtil.isBlank(email)) {
sendMail(email, "监控到" + host
+ "的geneftp出错!", "["
+ getdateFmt(System
.currentTimeMillis())
+ "]监控到" + host + "geneftp出错!");
System.out.println("send email");
}
}
map1.put(host, 0);
}
}
}
}
}
}
int i = 0;
for (Iterator it = map1.keySet().iterator(); it.hasNext();) {
String key = it.next().toString();
if (i == 0) {
writeLog(key + ":" + map1.get(key), false);
i++;
} else {
writeLog(key + ":" + map1.get(key), true);
}
}
}
private static void delFold(String txt){
String a = txt.substring(0,txt.lastIndexOf("\\\\")+2);
String b = txt.substring(txt.lastIndexOf("\\")-1);
String trueTxt = a + now + b;
File f = new File(trueTxt);
if(f.getParentFile().exists()){
f.getParentFile().delete();
}
}
private static String getTrueTxt(String txt){
String a = txt.substring(0,txt.lastIndexOf("\\\\")+2);
String b = txt.substring(txt.lastIndexOf("\\")-1);
String trueTxt = a + now + b;
File f = new File(trueTxt);
if(!f.getParentFile().exists()){
f.getParentFile().mkdirs();
}
return trueTxt;
}
private static void testGene6(String host, String port, String user,
String pwd, String txt) throws Exception {
FTPClient ftp = null;
ftp = new FTPClient();
// connection gene6ftp and download test.txt
ftp.setRemoteHost(host);
ftp.setRemotePort(Integer.parseInt(port));
ftp.connect();
ftp.login(user, pwd);
ftp.setConnectMode(FTPConnectMode.PASV);
ftp.setType(FTPTransferType.ASCII);
ftp.get(getTrueTxt(txt), "test.txt");
Thread.sleep(5000);
}
static Map<String, Integer> readLog() {
File f = new File(logPath);
if (!f.exists()) {
File fold = f.getParentFile();
if (!fold.exists())
fold.mkdirs();
String[] ips = genehosts.split(",");
for (String ip : ips) {
writeLog(ip + ":0", true);
}
}
Map<String, Integer> map = new HashMap<String, Integer>();
InputStreamReader read;
try {
read = new InputStreamReader(new FileInputStream(f), "gbk");
BufferedReader br = new BufferedReader(read);
String data = null;
while ((data = br.readLine()) != null) {
if (!StringUtil.isBlank(data)) {
String[] strs = data.split(":");
map.put(strs[0], Integer.valueOf(strs[1]));
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
return map;
}
}
static String getDayFmt(long date) {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
return sf.format(date);
}
static String getdateFmt(long date) {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sf.format(date);
}
public static boolean sendMail(String to, String subject, String body) {
// TODO Auto-generated method stub
SendMail sendMail = new SendMail();
sendMail.setSmtpServer(MAIL_SMTPSERVER);
sendMail.setPassword(MAIL_PASSWORD);
sendMail.setUser(MAIL_USER);
try {
sendMail.send(to, MAIL_FROM, subject, body);
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
static void writeLog(String data, boolean flag) {
OutputStreamWriter write = null;
BufferedWriter wr = null;
try {
File f1 = new File(logPath);
if (!f1.getParentFile().exists()) {
f1.getParentFile().mkdirs();
}
write = new OutputStreamWriter(new FileOutputStream(f1, flag));// true表示往下继续写
wr = new BufferedWriter(write);
wr.append(data + "\r\n");
wr.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
wr.close();
write.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static String loadProp(String prop) {
//InputStreamReader read;
// String data="";
String str = "";
InputStream is = Task.class.getClassLoader().getResourceAsStream(
"ApplicationResources.properties");
int i = 0;
byte[] buff = new byte[1024];
String text = "";
try {
while ((i = is.read(buff)) > 0) {
text = text + new String(buff, 0, i);
}
is.close();
String[] datas = text.split("\r\n");
for (String data : datas) {
if (!StringUtil.isBlank(data)) {
if (data.indexOf(prop) != -1 && data.indexOf("#") == -1) {
String[] strs = data.split("=");
str = strs[1].trim();
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
}finally{
return str;
}
/*
* try { File f = new
* File(Task.class.getClassLoader().getResource("ApplicationResources.properties").getPath());
* read = new InputStreamReader(new FileInputStream(f), "utf-8");
* BufferedReader br = new BufferedReader(read); while ((data =
* br.readLine()) != null) { if(data.indexOf(prop)!=-1 &&
* data.indexOf("#")==-1){ String[] strs = data.split("="); str =
* strs[1].trim(); } } } catch (Exception e) { e.printStackTrace();
* }finally{ return str; }
*/
}
}
ApplicationResources.properties:
gene6.ftp.hosts = 122.227.X.X,122.227.X.X
gene6.ftp.ports = 2129,2129
gene6.ftp.users = test,test
gene6.ftp.pwds = dimen123123,dimen123123
gene6.log.path = D:\\kdex\\Monitor_gene_server\\logs\\gene6d.log
gene6.test.txt.paths = D:\\kdex\\Monitor_gene_server\\get\\dl57.txt,D:\\kdex\\Monitor_gene_server\\get\\dl58.txt
schedule.fail.count = 3
schedule.send.emails = XXX@163.com,EEE@gmail.com,FFF@gmail.com
schedule.taskkill.flag = 0