我有一个非常奇怪的问题,我从未遇到过。我有一个字符串的ArrayList,其大小通常在800以上,具体取决于输入。但是,对于for-each循环或经典的for循环,循环只运行大约3-5次。 ArrayList填充了ssh输出行。我需要查看输出,连接字符串,并将它们放在数据库中。
processLogs方法(问题发生的地方)
public void processLogs(List<String> logs) {
try {
Connection conn = DMConnector.getDMConnection();
PreparedStatement statement = conn.prepareStatement("INSERT INTO Logs (to_address, status, smtp_transac, log_timestamp) VALUES (?,?,?,?)");
System.out.println(logs.size());
String to_address;
String status;
String smtp_transac;
String timestamp;
for (String log : logs) {
to_address = log.split(" <")[1].split("> ")[0];
status = log.split(" ")[2];
smtp_transac = log.split(">:")[1];
timestamp = log.split(" ")[0] + log.split(" ")[1];
statement.setString(1, to_address);
statement.setString(2, status);
statement.setString(3, smtp_transac);
statement.setString(4, timestamp);
statement.executeUpdate();
System.out.println("toAdd = " + to_address + " status= " + status + " smtp_transac = " + smtp_transac + "\n");
}
statement.close();
conn.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
运行上面的代码后,我只会在数据库中输入几行,而我的System.out只会多次打印。我也尝试使用带有statement.executeBatch()的statement.addBatch()和没有anvil的statement.executeQuery()。
以下是从控制台获取SSH线路的方法:
public List<String> getLogs() {
String remoteHostUserName = "";
String remoteHostPassword = "";
String hostIP = "";
List<String> results = new ArrayList<String>();
JSch jsch = new JSch();
try {
Session session = jsch.getSession(remoteHostUserName, hostIP, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// Skip prompting for the password info and go direct...
session.setPassword(remoteHostPassword);
session.connect();
String command = "hvmail_report -q all --last '1 min' -a --show-address --show-mtaid --show-time | sort";
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
System.out.println("Connect to session...");
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
//System.out.println(new String(tmp, 0, i));
Collections.addAll(results, new String(tmp, 0, i).split("\r\n|\r|\n"));
}
if (channel.isClosed()) {
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
ee.printStackTrace();
}
}
channel.disconnect();
session.disconnect();
if (in.markSupported()){
in.reset();
}
} catch (Exception e) {
System.out.println(e);
}
return results;
}
我唯一猜到为什么会发生这种情况与getLogs()方法有关。