[英]Using Scanner to display entire line if the line contains any part of a string match (Java)
所以我正在這個項目上分析特定文件簽名的十六進制轉儲。 我遇到的問題是嘗試分析大於16 GB的大型轉儲時,出現OutOfMemoryError:Java堆空間錯誤。 所以我的想法是重新設計我正在使用的算法。
現在,我的代碼看起來類似於:
public class Test
{
private static ArrayList<String> JPGHeaders = new ArrayList<String>();
private static ArrayList<String> JPGTrailers = new ArrayList<String>();
private static ArrayList<String> entireTextFile = new ArrayList<String>();
public static void main (String[] args)
{
Scanner scanner = new Scanner(new File("C:\\HexAnalyser\\HexDump\\fileTest.txt"));
while (scanner.hasNextLine())
{
entireTextFile.add(scanner.nextLine());
}
for (String line : entireTextFile)
{
if(line.contains(Constants.JPGHEADER))
{
JPGHeaders.add(line);
}
if(line.contains(Constants.JPGTRAILER))
{
JPGTrailers.add(line);
}
}
}
}
因此,它將整個文件添加到整個TextFile ArrayList中,然后在該ArrayList中搜索特定的文件頭和頭。
對於那些不知道典型的十六進制轉儲是什么樣的人,其類似於:
0012be0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
0012bf0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
0012c00: ffd8 ffe0 0010 4a46 4946 0001 0201 0050 ......JFIF.....P
0012c10: 0050 0000 ffed 166e 5068 6f74 6f73 686f .P.....nPhotosho
0012c20: 7020 332e 3000 3842 494d 03ed 0000 0000 p 3.0.8BIM......
0012c30: 0010 0050 0000 0001 0001 0050 0000 0001 ...P.......P....
0012c40: 0001 3842 494d 040d 0000 0000 0004 0000 ..8BIM..........
0012c50: 002d 3842 494d 03f3 0000 0000 0008 0000 .-8BIM..........
由於JPEG的標頭是“ ffd8 ffe0”,因此我想添加到JPGHeaders ArrayList的唯一一行是:
0012c00: ffd8 ffe0 0010 4a46 4946 0001 0201 0050 ......JFIF.....P
我知道這與Linux中的grep類似,但是我正在針對Windows平台上的Eclipse中完成的Java項目執行此操作。 有沒有更簡單的方法可以在最初掃描文件時搜索文件的每一行並將這些特定行添加到相應的arraylist中? 還是我將整個文件掃描到一個ArrayList中,然后在所述ArrayList中搜索字符串文字?
public class Test
{
private static ArrayList<String> JPGHeaders = new ArrayList<String>();
private static ArrayList<String> JPGTrailers = new ArrayList<String>();
private static ArrayList<String> entireTextFile = new ArrayList<String>();
public static void main (String[] args)
{
Scanner scanner = new Scanner(new File("C:\\HexAnalyser\\HexDump\\fileTest.txt"));
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
if(line.contains(Constants.JPGHEADER))
{
JPGHeaders.add(line);
}
if(line.contains(Constants.JPGTRAILER))
{
JPGTrailers.add(line);
}
}
}
}
為什么要將整個事情都保存在內存中? 閱讀該行后,請對其進行分析。 如果不相關,請將其丟棄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.