I am having a file of around 4MB, the file is an ascii file containing normal keyboard characters only. I tried many classes in java.io package to read the file contents as string. Reading them character by character (using FileReader and BufferedReader) takes approximately 40 seconds, reading the content using java.nio package (FileChannel and ByteBuffer) takes approximately 25 seconds. This is from my knowledge a little bit greater amount of time. Does someone knows any way to reduce this time consumption to somewhat around 10 seconds? Even solutions like creating file reader using C and calling from java will do. I used the below snippet to read the 4 MB file in 22 seconds-
public static String getContents(File file) {
try {
if (!file.exists() && !file.isFile()) {
return null;
}
FileInputStream in = new FileInputStream(file);
FileChannel ch = in.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(512);
Charset cs = Charset.forName("ASCII");
StringBuilder sb = new StringBuilder();
int rd;
while ((rd = ch.read(buf)) != -1) {
buf.rewind();
CharBuffer chbuf = cs.decode(buf);
for (int i = 0; i < chbuf.length(); i++) {
sb.append(chbuf.get());
}
buf.clear();
}
String contents = sb.toString();
System.out.println("File Contents:\n"+contents);
return contents;
} catch (Exception exception) {
System.out.println("Error:\n" + exception.getMessage());
return null;
}
}