Created
January 10, 2018 06:53
-
-
Save jeonguk/3e53e84280efd02868a6141f9f9d503e to your computer and use it in GitHub Desktop.
java scanner file read
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.jeonguk; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.util.Scanner; | |
import java.util.concurrent.TimeUnit; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
public class ScannerReadTest { | |
private static final Logger LOGGER = LoggerFactory.getLogger(ScannerReadTest.class); | |
public static void main(String[] args) { | |
if (args.length < 2) { | |
LOGGER.info("Usage: java filePath findWord"); | |
System.exit(1); | |
} | |
String filePath = args[0]; | |
String findWord = args[1]; | |
LOGGER.info("ScannerRead word contains line find "); | |
porcess(filePath, findWord); | |
} | |
/** | |
* This solution will iterate through all the lines in the file – allowing for processing of each line – | |
* without keeping references to them i.e. without keeping them in memory. | |
*/ | |
public static void porcess(final String filePath, final String findWord) { | |
long startTime = System.nanoTime(); | |
try (Scanner sc = new Scanner(new File(filePath), "UTF-8")) { | |
long freeMemoryBefore = Runtime.getRuntime().freeMemory(); | |
LOGGER.info("freeMemoryBefore {} ", freeMemoryBefore ); | |
while (sc.hasNextLine()) { | |
String line = sc.nextLine(); | |
if (line.contains(findWord)) { | |
LOGGER.info("line {} ", line ); | |
// parse line | |
//System.out.println(line); | |
} | |
} | |
// note that Scanner suppresses exceptions | |
if (sc.ioException() != null) { | |
sc.ioException().printStackTrace(); | |
} | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} | |
long endTime = System.nanoTime(); | |
long elapsedTimeInMillis = TimeUnit.MILLISECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS); | |
LOGGER.info("Completed in {} milliseconds", elapsedTimeInMillis); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
logback logging