下面是ListenPortAndRestartService.java的内容: ============================================================================ /* * @(#)Ping.java 1.2 01/12/13 * Connect to each of a list of hosts and measure the time required to complete * the connection. This example uses a selector and two additional threads in * order to demonstrate non-blocking connects and the multithreaded use of a * selector. * * Copyright 2001-2002 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * -Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduct the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that Software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. */ ============================================================= 文件太长,请合并下面的部分
import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.LinkedList; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.Date; import java.io.File; import java.text.SimpleDateFormat; import java.io.FileOutputStream; import java.io.RandomAccessFile; import java.util.Properties; import java.io.FileInputStream; import java.io.FileNotFoundException;class Ping { // The default daytime port static int DAYTIME_PORT = 8080; // The port we'll actually use static int port = DAYTIME_PORT; // Representation of a ping target // static class Target { InetSocketAddress address; SocketChannel channel; Exception failure; long connectStart; long connectFinish = 0; boolean shown = false; static boolean show = false; Target(String host) { try { address = new InetSocketAddress(InetAddress.getByName(host), port); } catch (IOException x) { failure = x; } } void show() { String result; if (connectFinish != 0) { result = Long.toString(connectFinish - connectStart) + "ms"; show = true; } else if (failure != null) { result = failure.toString(); show = false; } else { result = "Timed out"; show = false; } ListenPortAndRestartService.println(address + " : " + result); shown = true; } } // Thread for printing targets as they're heard from // static class Printer extends Thread { LinkedList pending = new LinkedList(); Printer() { setName("Printer"); setDaemon(true); } void add(Target t) { synchronized (pending) { pending.add(t); pending.notify(); } } public void run() { try { for (; ; ) { Target t = null; synchronized (pending) { while (pending.size() == 0) { pending.wait(); } t = (Target) pending.removeFirst(); } t.show(); } } catch (InterruptedException x) { return; } } } // Thread for connecting to all targets in parallel via a single selector // static class Connector extends Thread { Selector sel; Printer printer;// List of pending targets. We use this list because if we try to // register a channel with the selector while the connector thread is // blocked in the selector then we will block. // LinkedList pending = new LinkedList(); Connector(Printer pr) throws IOException { printer = pr; sel = Selector.open(); setName("Connector"); }// Initiate a connection sequence to the given target and add the // target to the pending-target list // void add(Target t) { SocketChannel sc = null; try {// Open the channel, set it to non-blocking, initiate connect sc = SocketChannel.open(); sc.configureBlocking(false); sc.connect(t.address);// Record the time we started t.channel = sc; t.connectStart = System.currentTimeMillis();// Add the new channel to the pending list synchronized (pending) { pending.add(t); }// Nudge the selector so that it will process the pending list sel.wakeup(); } catch (IOException x) { if (sc != null) { try { sc.close(); } catch (IOException xx) {} } t.failure = x; printer.add(t); } }// Process any targets in the pending list // void processPendingTargets() throws IOException { synchronized (pending) { while (pending.size() > 0) { Target t = (Target) pending.removeFirst(); try {// Register the channel with the selector, indicating // interest in connection completion and attaching the // target object so that we can get the target back // after the key is added to the selector's // selected-key set t.channel.register(sel, SelectionKey.OP_CONNECT, t); } catch (IOException x) {// Something went wrong, so close the channel and // record the failure t.channel.close(); t.failure = x; printer.add(t); } } } }// Process keys that have become selected // void processSelectedKeys() throws IOException { for (Iterator i = sel.selectedKeys().iterator(); i.hasNext(); ) {// Retrieve the next key and remove it from the set SelectionKey sk = (SelectionKey) i.next(); i.remove();// Retrieve the target and the channel Target t = (Target) sk.attachment(); SocketChannel sc = (SocketChannel) sk.channel();// Attempt to complete the connection sequence try { if (sc.finishConnect()) { sk.cancel(); t.connectFinish = System.currentTimeMillis(); sc.close(); printer.add(t); } } catch (IOException x) { sc.close(); t.failure = x; printer.add(t); } } } volatile boolean shutdown = false;// Invoked by the main thread when it's time to shut down // void shutdown() { shutdown = true; sel.wakeup(); }// Connector loop // public void run() { for (; ; ) { try { int n = sel.select(); if (n > 0) { processSelectedKeys(); } processPendingTargets(); if (shutdown) { sel.close(); return; } } catch (IOException x) { x.printStackTrace(); } } } } private static Printer printer; public static boolean pingRemoteHost(String hostName, int port) throws InterruptedException, IOException { Ping.port = port;// Create the threads and start them up if (printer == null) { printer = new Printer(); printer.start(); } Connector connector = new Connector(printer); connector.start();// Create the targets and add them to the connector LinkedList targets = new LinkedList(); Target t = new Target(hostName); targets.add(t); connector.add(t);// Wait for everything to finish Thread.sleep(300); connector.shutdown(); connector.join();// Print status of targets that have not yet been shown for (Iterator i = targets.iterator(); i.hasNext(); ) { Target t1 = (Target) i.next(); if (!t1.shown) { t.show(); } } return Target.show; } } ======================================================== 文件太长,请合并下面的部分
好长啊;可是jboss下有个log目录,里面有详细的信息,你可以用记事本打开仔细阅读的
class StreamGobbler extends Thread { InputStream is; String type; StreamGobbler(InputStream is, String type) { this.is = is; this.type = type; } public void run() { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ( (line = br.readLine()) != null) ListenPortAndRestartService.println(type + ">" + line); } catch (IOException ioe) { ioe.printStackTrace(); } } }public class ListenPortAndRestartService { private static String filePath = "/opt/jboss-3.2.6/server/default/deploy/myApplication.war/log";//"D:"; public static void main(String[] args) throws InterruptedException { String filePathConfig = "/opt/ensureJBoss/restartJBossService.properties";//"D:\\dd.properties"; String cmd1 = "sh";//"cmd.exe"; String cmd2 = "-c";//"/C"; String cmd31 = "/opt/jboss-3.2.6/bin/shutdown.sh -S";//"D:\\backup\\jboss-3.2.6\\bin\\shutdown.bat -S"; String cmd32 = "export LD_LIBRARY_PATH=/opt/smslib";//"dir"; // String cmd33 = "/opt/jboss-3.2.6/bin/run.sh &";//"D:\\backup\\jboss-3.2.6\\bin\\run.bat"; // String ip = "localhost"; int port = 8080; while (true) { boolean needListen = false; ListenPortAndRestartService listen = new ListenPortAndRestartService(); String need = listen.getProperties(filePathConfig).getProperty( "needListen"); if (need.equalsIgnoreCase("false")) { needListen = false; } else if (need.equalsIgnoreCase("true")) { needListen = true; } while (needListen) { try { boolean pingResult = Ping.pingRemoteHost(ip, port); println("" + pingResult); if (!pingResult) { String osName = System.getProperty("os.name"); println(osName); String[] cmd = new String[3]; Date start = new Date(); println(start + ":JBoss shutdown,need restart..........."); println("First,shutdown..................."); cmd[0] = cmd1; cmd[1] = cmd2; cmd[2] = cmd31; Runtime rt = Runtime.getRuntime(); println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]); Process proc = rt.exec(cmd); // any error message? StreamGobbler errorGobbler = new StreamGobbler(proc. getErrorStream(), "ERROR"); // any output? StreamGobbler outputGobbler = new StreamGobbler(proc. getInputStream(), "OUTPUT"); // kick them off errorGobbler.start(); outputGobbler.start(); Thread.sleep(30000); println("Second,export..................."); cmd[0] = cmd1; cmd[1] = cmd2; cmd[2] = cmd32; rt = Runtime.getRuntime(); println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]); proc = rt.exec(cmd); // any error message? errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // any output? outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); // kick them off errorGobbler.start(); outputGobbler.start(); println( "Third,run........................"); cmd[0] = cmd1; cmd[1] = cmd2; cmd[2] = cmd33; rt = Runtime.getRuntime(); println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]); proc = rt.exec(cmd); // any error message? errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // any output? outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); // kick them off errorGobbler.start(); outputGobbler.start(); Date end = new Date(); println(end + ":JBoss restart successful..........."); } Thread.sleep(30000); need = listen.getProperties(filePathConfig).getProperty( "needListen"); if (need.equalsIgnoreCase("false")) { needListen = false; } else if (need.equalsIgnoreCase("true")) { needListen = true; } } catch (Throwable t) { t.printStackTrace(); } } if (!needListen) { Thread.sleep(30000); println("service has been closed............."); } } } static void println(String fileContent) { /** * 取得项目路径,如果路径不存在。则新建路径 */ String fileName = "restartJBoss" + new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis())) + ".log"; File path = new File(filePath); if (!path.exists()) { path.mkdir(); } File file = new File(path, fileName); //如果文件长度大于10M,则改名成备份文件进行存储。 if (file.length() > 10 * 1024 * 1024) { String rename = fileName + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis())); file.renameTo(new File(path, rename)); } try { byte[] temp = { 10, 10}; byte[] contentdb = fileContent.getBytes("gb2312"); byte[] content = new byte[contentdb.length + temp.length]; System.arraycopy(contentdb, 0, content, 0, contentdb.length); System.arraycopy(temp, 0, content, contentdb.length, temp.length); if (file.exists()) { //如果文件存在。则使用随机读写文件用RandomAccessFile类去定义到文件尾后写一条记录 RandomAccessFile accessFile = null; accessFile = new RandomAccessFile(file, "rw"); accessFile.seek(file.length()); accessFile.write(content); accessFile.close(); } else { //如果文件不存在。则使用写文件流一次性写入。 FileOutputStream stream = new FileOutputStream(file); stream.write(content, 0, content.length); stream.close(); } } catch (IOException ie) { ie.printStackTrace(); } } private Properties getProperties(String config) { Properties properties = new Properties(); FileInputStream fileinputstream = null; try { fileinputstream = new FileInputStream(config); } catch (FileNotFoundException e) { println(e.getMessage()); } try { if (fileinputstream != null) { properties.load(fileinputstream); fileinputstream.close(); } } catch (IOException e) { println(e.getMessage()); } return properties; } } ======================================================== 完
to crazycy(崔毅):日志我必然看过了,但日志没有任何用得着的信息所以出此下策,24*7在线运行的系统,首先得保证它运行==================================================其实后来我写完并启动这个服务之后,jboss一直运行良好,真搞笑
正解,可能日志里根本不能看到错误,
郁闷的很
那么就先执行shutdown,关闭jboss,再执行run来开启jboss代码写在一个文件中,命名为ListenPortAndRestartService.java,用到的资源文件为restartJBossService.properties,内容如下:
needListen=true
============================================================================
/*
* @(#)Ping.java 1.2 01/12/13
* Connect to each of a list of hosts and measure the time required to complete
* the connection. This example uses a selector and two additional threads in
* order to demonstrate non-blocking connects and the multithreaded use of a
* selector.
*
* Copyright 2001-2002 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY
* DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR
* RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR
* ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE
* FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT,
* SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF
* THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or
* intended for use in the design, construction, operation or
* maintenance of any nuclear facility.
*/
=============================================================
文件太长,请合并下面的部分
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.LinkedList;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.Date;
import java.io.File;
import java.text.SimpleDateFormat;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileNotFoundException;class Ping { // The default daytime port
static int DAYTIME_PORT = 8080; // The port we'll actually use
static int port = DAYTIME_PORT; // Representation of a ping target
//
static class Target { InetSocketAddress address;
SocketChannel channel;
Exception failure;
long connectStart;
long connectFinish = 0;
boolean shown = false;
static boolean show = false;
Target(String host) {
try {
address = new InetSocketAddress(InetAddress.getByName(host),
port);
}
catch (IOException x) {
failure = x;
}
} void show() {
String result;
if (connectFinish != 0) {
result = Long.toString(connectFinish - connectStart) + "ms";
show = true;
}
else if (failure != null) {
result = failure.toString();
show = false;
}
else {
result = "Timed out";
show = false;
}
ListenPortAndRestartService.println(address + " : " + result);
shown = true;
} } // Thread for printing targets as they're heard from
//
static class Printer
extends Thread {
LinkedList pending = new LinkedList(); Printer() {
setName("Printer");
setDaemon(true);
} void add(Target t) {
synchronized (pending) {
pending.add(t);
pending.notify();
}
} public void run() { try { for (; ; ) {
Target t = null;
synchronized (pending) { while (pending.size() == 0) {
pending.wait();
} t = (Target) pending.removeFirst();
}
t.show();
} } catch (InterruptedException x) {
return;
} } } // Thread for connecting to all targets in parallel via a single selector
//
static class Connector
extends Thread {
Selector sel;
Printer printer;// List of pending targets. We use this list because if we try to
// register a channel with the selector while the connector thread is
// blocked in the selector then we will block.
//
LinkedList pending = new LinkedList(); Connector(Printer pr) throws IOException {
printer = pr;
sel = Selector.open();
setName("Connector");
}// Initiate a connection sequence to the given target and add the
// target to the pending-target list
//
void add(Target t) {
SocketChannel sc = null;
try {// Open the channel, set it to non-blocking, initiate connect
sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(t.address);// Record the time we started
t.channel = sc;
t.connectStart = System.currentTimeMillis();// Add the new channel to the pending list
synchronized (pending) {
pending.add(t);
}// Nudge the selector so that it will process the pending list
sel.wakeup(); }
catch (IOException x) {
if (sc != null) {
try {
sc.close();
}
catch (IOException xx) {}
}
t.failure = x;
printer.add(t);
}
}// Process any targets in the pending list
//
void processPendingTargets() throws IOException {
synchronized (pending) {
while (pending.size() > 0) {
Target t = (Target) pending.removeFirst();
try {// Register the channel with the selector, indicating
// interest in connection completion and attaching the
// target object so that we can get the target back
// after the key is added to the selector's
// selected-key set
t.channel.register(sel, SelectionKey.OP_CONNECT, t); }
catch (IOException x) {// Something went wrong, so close the channel and
// record the failure
t.channel.close();
t.failure = x;
printer.add(t); } }
}
}// Process keys that have become selected
//
void processSelectedKeys() throws IOException {
for (Iterator i = sel.selectedKeys().iterator(); i.hasNext(); ) {// Retrieve the next key and remove it from the set
SelectionKey sk = (SelectionKey) i.next();
i.remove();// Retrieve the target and the channel
Target t = (Target) sk.attachment();
SocketChannel sc = (SocketChannel) sk.channel();// Attempt to complete the connection sequence
try {
if (sc.finishConnect()) {
sk.cancel();
t.connectFinish = System.currentTimeMillis();
sc.close();
printer.add(t);
}
}
catch (IOException x) {
sc.close();
t.failure = x;
printer.add(t);
}
}
} volatile boolean shutdown = false;// Invoked by the main thread when it's time to shut down
//
void shutdown() {
shutdown = true;
sel.wakeup();
}// Connector loop
//
public void run() {
for (; ; ) {
try {
int n = sel.select();
if (n > 0) {
processSelectedKeys();
}
processPendingTargets();
if (shutdown) {
sel.close();
return;
}
}
catch (IOException x) {
x.printStackTrace();
}
}
} } private static Printer printer;
public static boolean pingRemoteHost(String hostName, int port) throws
InterruptedException, IOException {
Ping.port = port;// Create the threads and start them up
if (printer == null) {
printer = new Printer();
printer.start();
} Connector connector = new Connector(printer);
connector.start();// Create the targets and add them to the connector
LinkedList targets = new LinkedList();
Target t = new Target(hostName);
targets.add(t);
connector.add(t);// Wait for everything to finish
Thread.sleep(300);
connector.shutdown();
connector.join();// Print status of targets that have not yet been shown
for (Iterator i = targets.iterator(); i.hasNext(); ) {
Target t1 = (Target) i.next();
if (!t1.shown) {
t.show();
}
}
return Target.show;
}
}
========================================================
文件太长,请合并下面的部分
extends Thread {
InputStream is;
String type; StreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
} public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ( (line = br.readLine()) != null)
ListenPortAndRestartService.println(type + ">" + line);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}public class ListenPortAndRestartService {
private static String filePath = "/opt/jboss-3.2.6/server/default/deploy/myApplication.war/log";//"D:";
public static void main(String[] args) throws InterruptedException {
String filePathConfig = "/opt/ensureJBoss/restartJBossService.properties";//"D:\\dd.properties";
String cmd1 = "sh";//"cmd.exe";
String cmd2 = "-c";//"/C";
String cmd31 = "/opt/jboss-3.2.6/bin/shutdown.sh -S";//"D:\\backup\\jboss-3.2.6\\bin\\shutdown.bat -S";
String cmd32 = "export LD_LIBRARY_PATH=/opt/smslib";//"dir"; //
String cmd33 = "/opt/jboss-3.2.6/bin/run.sh &";//"D:\\backup\\jboss-3.2.6\\bin\\run.bat"; //
String ip = "localhost";
int port = 8080;
while (true) {
boolean needListen = false;
ListenPortAndRestartService listen = new ListenPortAndRestartService();
String need = listen.getProperties(filePathConfig).getProperty(
"needListen");
if (need.equalsIgnoreCase("false")) {
needListen = false;
}
else if (need.equalsIgnoreCase("true")) {
needListen = true;
} while (needListen) {
try {
boolean pingResult = Ping.pingRemoteHost(ip, port);
println("" + pingResult);
if (!pingResult) {
String osName = System.getProperty("os.name");
println(osName);
String[] cmd = new String[3];
Date start = new Date();
println(start + ":JBoss shutdown,need restart...........");
println("First,shutdown...................");
cmd[0] = cmd1;
cmd[1] = cmd2;
cmd[2] = cmd31;
Runtime rt = Runtime.getRuntime();
println("Execing " + cmd[0] + " " + cmd[1]
+ " " + cmd[2]);
Process proc = rt.exec(cmd);
// any error message?
StreamGobbler errorGobbler = new
StreamGobbler(proc.
getErrorStream(),
"ERROR"); // any output?
StreamGobbler outputGobbler = new
StreamGobbler(proc.
getInputStream(),
"OUTPUT"); // kick them off
errorGobbler.start();
outputGobbler.start(); Thread.sleep(30000);
println("Second,export...................");
cmd[0] = cmd1;
cmd[1] = cmd2;
cmd[2] = cmd32; rt = Runtime.getRuntime();
println("Execing " + cmd[0] + " " + cmd[1]
+ " " + cmd[2]);
proc = rt.exec(cmd);
// any error message?
errorGobbler = new
StreamGobbler(proc.getErrorStream(),
"ERROR"); // any output?
outputGobbler = new
StreamGobbler(proc.getInputStream(),
"OUTPUT"); // kick them off
errorGobbler.start();
outputGobbler.start();
println(
"Third,run........................");
cmd[0] = cmd1;
cmd[1] = cmd2;
cmd[2] = cmd33; rt = Runtime.getRuntime();
println("Execing " + cmd[0] + " " + cmd[1]
+ " " + cmd[2]);
proc = rt.exec(cmd);
// any error message?
errorGobbler = new
StreamGobbler(proc.getErrorStream(),
"ERROR"); // any output?
outputGobbler = new
StreamGobbler(proc.getInputStream(),
"OUTPUT"); // kick them off
errorGobbler.start();
outputGobbler.start();
Date end = new Date();
println(end + ":JBoss restart successful...........");
}
Thread.sleep(30000);
need = listen.getProperties(filePathConfig).getProperty(
"needListen");
if (need.equalsIgnoreCase("false")) {
needListen = false;
}
else if (need.equalsIgnoreCase("true")) {
needListen = true;
}
}
catch (Throwable t) {
t.printStackTrace();
}
} if (!needListen) {
Thread.sleep(30000);
println("service has been closed.............");
}
}
} static void println(String fileContent) {
/**
* 取得项目路径,如果路径不存在。则新建路径
*/ String fileName = "restartJBoss" +
new SimpleDateFormat("yyyy-MM-dd").format(new
Date(System.currentTimeMillis())) +
".log";
File path = new File(filePath);
if (!path.exists()) {
path.mkdir();
}
File file = new File(path, fileName);
//如果文件长度大于10M,则改名成备份文件进行存储。
if (file.length() > 10 * 1024 * 1024) {
String rename = fileName +
new SimpleDateFormat("yyyyMMddHHmmss").format(new
Date(System.currentTimeMillis()));
file.renameTo(new File(path, rename)); }
try {
byte[] temp = {
10, 10};
byte[] contentdb = fileContent.getBytes("gb2312");
byte[] content = new byte[contentdb.length + temp.length];
System.arraycopy(contentdb, 0, content, 0, contentdb.length);
System.arraycopy(temp, 0, content, contentdb.length, temp.length);
if (file.exists()) {
//如果文件存在。则使用随机读写文件用RandomAccessFile类去定义到文件尾后写一条记录
RandomAccessFile accessFile = null;
accessFile = new RandomAccessFile(file, "rw");
accessFile.seek(file.length());
accessFile.write(content);
accessFile.close();
}
else {
//如果文件不存在。则使用写文件流一次性写入。
FileOutputStream stream = new FileOutputStream(file);
stream.write(content, 0, content.length);
stream.close();
}
}
catch (IOException ie) {
ie.printStackTrace();
}
} private Properties getProperties(String config) {
Properties properties = new Properties();
FileInputStream fileinputstream = null;
try {
fileinputstream = new FileInputStream(config);
}
catch (FileNotFoundException e) {
println(e.getMessage());
}
try {
if (fileinputstream != null) {
properties.load(fileinputstream);
fileinputstream.close();
}
}
catch (IOException e) {
println(e.getMessage());
}
return properties;
}
}
========================================================
完