File Search
Approaches
A simple technique that could well be considerably faster than indexOf() is to use a Scanner, with the method findWithinHorizon(). If you use a constructor that takes a File object, Scanner will internally make a FileChannel to read the file. And for pattern matching it will end up using a Boyer-Moore algorithm for efficient string searching.
I think this program still loads the whole file into memory. I am facing OOM exceptions when trying with large files.
Another link
public static void searchFile() {
//File file = new File("C:\\Data\\wwwData\\_backup\\full_04.2022\\auth.log");
File file = new File("C:\\Data\\wwwData\\_backup\\full_04.2022\\lib\\mysql_bak\\ibdata1");
System.out.println("Start");
try {
int count = 0;
FileReader fileIn = new FileReader(file);
BufferedReader reader = new BufferedReader(fileIn);
String line;
while((line = reader.readLine()) != null) {
if((line.contains("pydct"))) {
System.out.println("Line number " + count);
}
count++;
}
reader.close();
}catch (IOException e){
System.out.println(e);
}
System.out.println("Finish");
}
public static void searchFile2() {
int tot = 0;
System.out.println("Start");
Pattern pattern = Pattern.compile("BARCELONA");
try {
Scanner scan = new Scanner(new File("C:\\Data\\wwwData\\_backup\\full_04.2022\\lib\\mysql_bak\\ibdata1"));
while (scan.findWithinHorizon(pattern, 0) != null)
tot++;
}catch (FileNotFoundException e){
System.out.println(e);
}
System.out.println("Results found: " + tot);
}
Crop String
public static String cropString(String s, int k) {
if(k < 1) return "";
if(k >= s.length()) return s;
String part = s.substring(0, k+1);
return part.substring(0, part.lastIndexOf(" "));
}
public static String cropString1(String s, int k) {
if(k < 1) return "";
if(k >= s.length()) return s;
while(s.charAt(k) != ' ')
k--;
return s.substring(0, k);
}