您好我需要从 java 执行 vi 命令并需要存储到本地文件中。我正在使用 jcraft.jsch
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class ViDAO {
public boolean mergeLogs(String hostName, String logFile, String userName,
String password) {
System.out.println("in VIdao" + hostName);
String command = null;
final int MAXREAD = 131072 * 100;
try {
command = "cd /dr/logs/sonic/dmbain1;view " + logFile;
JSch jsch = new JSch();
Session session = jsch.getSession(userName, hostName, 22);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword("Janu$113");
session.connect();
/* System.out.println("Connected to******* " + host+"*********");*/
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setXForwarding(true);
channel.connect();
InputStream in = channel.getInputStream();
byte[] tmp = new byte[MAXREAD];
File dir = new File("C:\\Documents and Settings\\" +
System.getProperty("user.name") +
"\\Desktop\\LogFiles");
dir.mkdir();
File f;
f=new File("C:\\Documents and Settings\\" +
System.getProperty("user.name") +
"\\Desktop\\LogFiles\\" +
logFile + ".txt");
if(!f.exists()){
f.createNewFile();
}
BufferedWriter out = new BufferedWriter(new FileWriter(f));
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, MAXREAD);
if (i < 0)
break;
String strResult = new String(tmp, 0, i);
out.write(strResult+"\n");
System.out.println(strResult);
}
if (channel.isClosed()) {
in.close();
break;
}
}
System.out.println("completed");
channel.disconnect();
session.disconnect();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
public static void main(String[] args) {
}
}
在这里,我无法读取文件,只有我能够读取的几行代码,请对此提供帮助。当我使用tail命令而不是vi时,它的工作但处理时间很长。如果我使用vi命令,我只能打印一些行。
请帮忙...