我是java的新手本周就学会了,我老师要我解析以文本文件格式保存的HTTP请求。基本上他想要我提取 只需这一行“GET / fenway / HTTP / 1.0 \ r \ n”和“主持人:www.redsox.com \ r \ n” 并以文本格式保存。 我的程序运行不正常,因为它包含错误。我做的是逐行读取文本文件,然后将其输入到一个函数,该函数尝试读取缓冲区并对每个单词进行标记并将其保存到copyGetWord,然后运行while循环以检测单词“GET”是否为发现它会将getWord存储到一个arraylist。
另一件事是我只允许使用java来实现这个没有perl或python。此外,我已经尝试过jnetpcap库,但是在安装它们时遇到问题,因此我遇到了文本文件。
希望任何人都可以提供帮助。
传输控制协议,Src端口:bridgecontrol(1073),Dst端口:http(80),Seq:1,Ack:1,Len:270 超文本传输协议 GET / azur / HTTP / 1.0 \ r \ n 连接:Keep-Alive \ r \ n User-Agent: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和Displays 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)
答案 0 :(得分:1)
你的while循环是个问题。试试这个:
String readBufLine = bufferPcap.readLine();
while (readBufLine!=null){
StoreLine.add(readBufLine);
handle.LookForWord(readBufLine);
readBufLine = bufferPcap.readLine();
}
bufferPcap.close();
这读取缓冲区中的行并且在读取行不为空时循环 - 新行始终被读取为循环体的最后一个操作,以便循环的下一次迭代将检查读取行在尝试对其进行标记之前不为空。