使用java在远程目录上的服务器日志文件中搜索模式
我想在远程目录中的一些日志文件中搜索一个字符串模式,结果,我想要文件名、行号/字符串的出现。我有一个文件路径、服务器地址、凭据和要搜索的字符串数组。我从中获得了一些apache日志解析器的代码。是否有任何方法可以解析文件,而无需在远程计算机上安装任何东西作为运行解析代码的代理 您想要的是“模仿”著名的使用java在远程目录上的服务器日志文件中搜索模式,java,apache,jakarta-ee,open-source,Java,Apache,Jakarta Ee,Open Source,我想在远程目录中的一些日志文件中搜索一个字符串模式,结果,我想要文件名、行号/字符串的出现。我有一个文件路径、服务器地址、凭据和要搜索的字符串数组。我从中获得了一些apache日志解析器的代码。是否有任何方法可以解析文件,而无需在远程计算机上安装任何东西作为运行解析代码的代理 您想要的是“模仿”著名的grep程序。“谷歌搜索”我从一个Oracle示例中找到了一个示例。本课程的目标是: 在文件列表中搜索与给定正则表达式模式匹配的行 但是,正如您所看到的,这是Java的1.4.2版本,您可能需要自己
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);
}
}
}
我希望这有帮助。干杯欢迎来到Stack Overflow!我们鼓励你这样做。如果你有,请将其添加到问题中-如果没有,请先研究并尝试你的问题,然后再回来。我们不可能知道这一点