我想在远程目录中的一些日志文件中搜索字符串模式,因此,我想要文件名、行号/字符串的出现。我有一组文件路径、服务器地址、凭据和要搜索的字符串。我从这里得到了一些 apache 日志解析器的代码。有什么方法可以解析文件而不在远程机器上安装任何东西作为运行我的解析代码的代理?
问问题
1675 次
1 回答
1
您想要的是“模仿”著名的grep
程序。“谷歌搜索”我从一个 Oracle 示例中找到了这个示例。该课程的目标是:
在文件列表中搜索与给定正则表达式模式匹配的行。
但是,正如您所看到的,这是来自 Java 的 1.4.2 版本,您可能必须自己更新它。这是课程:
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.regex.*;
public class Grep {
// Charset and decoder for ISO-8859-15
private static Charset charset = Charset.forName("ISO-8859-15");
private static CharsetDecoder decoder = charset.newDecoder();
// Pattern used to parse lines
private static Pattern linePattern = Pattern.compile(".*\r?\n");
// The input pattern that we're looking for
private static Pattern pattern;
// Compile the pattern from the command line
//
private static void compile(String pat) {
try {
pattern = Pattern.compile(pat);
} catch (PatternSyntaxException x) {
System.err.println(x.getMessage());
System.exit(1);
}
}
// Use the linePattern to break the given CharBuffer into lines, applying
// the input pattern to each line to see if we have a match
//
private static void grep(File f, CharBuffer cb) {
Matcher lm = linePattern.matcher(cb); // Line matcher
Matcher pm = null; // Pattern matcher
int lines = 0;
while (lm.find()) {
lines++;
CharSequence cs = lm.group(); // The current line
if (pm == null)
pm = pattern.matcher(cs);
else
pm.reset(cs);
if (pm.find())
System.out.print(f + ":" + lines + ":" + cs);
if (lm.end() == cb.limit())
break;
}
}
// Search for occurrences of the input pattern in the given file
//
private static void grep(File f) throws IOException {
// Open the file and then get a channel from the stream
FileInputStream fis = new FileInputStream(f);
FileChannel fc = fis.getChannel();
// Get the file's size and then map it into memory
int sz = (int)fc.size();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
// Decode the file into a char buffer
CharBuffer cb = decoder.decode(bb);
// Perform the search
grep(f, cb);
// Close the channel and the stream
fc.close();
}
要使用它来 grep 目录中的所有文件,您可以使用:
public void listFilesInDirectory(File dir) {
File[] files = dir.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
listFilesInDirectory(f);
}
else
Grep.grep(f);
}
}
}
我希望它有所帮助。干杯
于 2012-11-06T13:06:58.193 回答