前段时间写了个程序需要对文件进行读取操作,一开始使用最普通的写法
但是当正式开始运行的时候发现用是可以用但效率过于低下(因为每次运行都要读取几十甚至上百个的文件,所以效率问题很明显),所以就上网搜索了一些提高IO流的资料,发现大多数都是说使用缓存,于是就上网搜了一段代码
- FileReader in = new FileReader("E:/a.html");
- BufferedReader br = new BufferedReader(in);
- String string="",str="";
- while((string=br.readLine())!=null){
- str+=string;
- }
- System.out.println(str);
FileReader in = new FileReader("E:/a.html");
BufferedReader br = new BufferedReader(in);
String string="",str="";
while((string=br.readLine())!=null){
str+=string;
}
System.out.println(str);
但是当正式开始运行的时候发现用是可以用但效率过于低下(因为每次运行都要读取几十甚至上百个的文件,所以效率问题很明显),所以就上网搜索了一些提高IO流的资料,发现大多数都是说使用缓存,于是就上网搜了一段代码
- * 使用缓存区读写文件
- * @param from
- * @param to
- * @throws IOException
- */
- public static void readWriteWithBuffer(String from, String to)
- throws IOException {
- InputStream inBuffer = null;
- OutputStream outBuffer = null;
- try {
- inBuffer = new BufferedInputStream(new FileInputStream(from));
- outBuffer = new BufferedOutputStream(new FileOutputStream(to));
- while (true) {
- int data = inBuffer.read();
- if (data == -1) {
- break;
- }
- outBuffer.write(data);
- }
- } finally {
- if (inBuffer != null) {
- inBuffer.close();
- }
- if (outBuffer != null) {
- outBuffer.close();
- }
- }
- }
- }
* 使用缓存区读写文件
* @param from
* @param to
* @throws IOException
*/
public static void readWriteWithBuffer(String from, String to)
throws IOException {
InputStream inBuffer = null;
OutputStream outBuffer = null;
try {
inBuffer = new BufferedInputStream(new FileInputStream(from));
outBuffer = new BufferedOutputStream(new FileOutputStream(to));
while (true) {
int data = inBuffer.read();
if (data == -1) {
break;
}
outBuffer.write(data);
}
} finally {
if (inBuffer != null) {
inBuffer.close();
}
if (outBuffer != null) {
outBuffer.close();
}
}
}
}