我是java新手,这周刚学,我的老师要我解析一个以文本文件格式保存的HTTP请求。基本上他想让我只提取
这行“GET /fenway/ HTTP/1.0\r\n”和这个“主机:www.redsox.com\r\n”并将其保存为文本格式。我的程序还不能很好地运行,因为它包含错误。我所做的是逐行读取文本文件,然后将其输入到一个函数中,该函数尝试读取缓冲区并标记每个单词并将其保存到 copyGetWord,然后运行一个 while 循环来检测单词“GET”是否是发现它将getWord存储到一个arraylist。
另一件事是我只允许在没有 perl 或 python 的情况下使用 java。我也尝试过 jnetpcap 库,但安装它们时遇到问题,所以我被文本文件卡住了。
希望任何人都可以提供帮助。
这是一个示例文本文件:
传输控制协议,Src 端口:bridgecontrol (1073),Dst 端口:http (80),Seq:1,Ack:1,Len:270 超文本传输协议 GET /azur/ HTTP/1.0\r\n 连接:Keep-Alive \r\n 用户代理:Mozilla/4.08 [en] (WinNT; I)\r\n 主机:www.google.com\r\n
public static void main(String[] args) {
System.out.println("Tries to read the samplepcap1.txt, \n");
ReadingFile1 handle = new ReadingFile1();
ArrayList <String> StoreLine = new ArrayList<String>();
try{
FileReader ReadPcap = new FileReader("samplePcapSmall.txt");
BufferedReader bufferPcap = new BufferedReader(ReadPcap);
String readBufLine = bufferPcap.readLine();
StoreLine.add(readBufLine);
while (readBufLine!=null){
readBufLine = bufferPcap.readLine();
handle.LookForWord(readBufLine);
}
bufferPcap.close();
}
catch (FileNotFoundException e){
System.out.println("\nFile not found");
}
catch (IOException e){
System.out.println("Problem reading the file.\n");
}
}
public String LookForWord(String getWord){
ArrayList <String>MatchingWord = new ArrayList<String>();
StringTokenizer copyGetWord = new StringTokenizer(getWord," ");
while (copyGetWord.hasMoreElements()){
if(copyGetWord.nextToken().matches("GET")){
MatchingWord.add(getWord);
}
}
System.out.println("\nMatch: "+MatchingWord);
return getWord;
}
尝试读取 samplepcap1.txt,存储在 ArrayList 中并显示 ArrayList
Match: []
Match: [ GET /fenway/ HTTP/1.0\r\n]
Match: []
Match: []
Match: []
Exception in thread "main" java.lang.NullPointerException
at java.util.StringTokenizer.<init>(StringTokenizer.java:182)
at java.util.StringTokenizer.<init>(StringTokenizer.java:204)
at readingfile1.ReadingFile1.LookForWord(ReadingFile1.java:84)
at readingfile1.ReadingFile1.main(ReadingFile1.java:62)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)