import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Test {
public static ArrayList<StringBuffer> readCharStream(String fileName)
throws IOException {
ArrayList<StringBuffer> list = new ArrayList<StringBuffer>();
FileReader fileReader = null;
try {
fileReader = new FileReader(fileName);
int data = 0;
StringBuffer stringBuffer = new StringBuffer();
while ((data = fileReader.read()) != -1) {
if (data == '\n' || data == '\r') {
list.add(stringBuffer);
stringBuffer = new StringBuffer();
} else {
stringBuffer.append((char) data);
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fileReader != null) {
fileReader.close();
}
}
return list;
}
public static String readCharStreamWithBuffer(String fileName)
throws IOException {
StringBuffer retVal = new StringBuffer();
FileReader fileReader = null;
try {
fileReader = new FileReader(fileName);
final int BUFFER_SIZE = 1024 * 1024;
char[] readBuffer = new char[BUFFER_SIZE];
int resultSize = 0;
while ((resultSize = fileReader.read(readBuffer)) != -1) {
if (resultSize == BUFFER_SIZE) {
retVal.append(readBuffer);
} else {
for (int i = 0; i < resultSize; i++) {
retVal.append(readBuffer[i]);
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fileReader != null) {
fileReader.close();
}
}
return retVal.toString();
}
public static ArrayList<String> readBufferedReader(String fileName)
throws IOException {
ArrayList<String> list = new ArrayList<String>();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(fileName));
String data;
while ((data = bufferedReader.readLine()) != null) {
list.add(data);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
return list;
}
public static void main(String[] args) throws IOException {
final String fileName = "D:\\Test.java";
long startTime = System.nanoTime();
readCharStream(fileName);
long endTime = System.nanoTime();
double elaspedTime = (endTime - startTime) / 1000000.0;
System.out.println(elaspedTime);
startTime = System.nanoTime();
readCharStreamWithBuffer(fileName);
endTime = System.nanoTime();
elaspedTime = (endTime - startTime) / 1000000.0;
System.out.println(elaspedTime);
startTime = System.nanoTime();
readBufferedReader(fileName);
endTime = System.nanoTime();
elaspedTime = (endTime - startTime) / 1000000.0;
System.out.println(elaspedTime);
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.