---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------
readLine()--java.io.BufferedReader中用于读取一行的方法
实现原理:一般是在readLine()方法内部建立一个数字,然后使用reader节点流(比如FileReader类)的read()方法读取一个字符,然后判断是否是行结束符,如果不是就存到数组中,接着读下一个;如果是行结束符,就将数组的内容以字符串形式返回。
下面,根据这个原理,来自我模拟一个readLine()方法:
package Day19_io;
import java.io.FileReader;
import java.io.IOException;
// 建立自己的BufferedReader
public class MyBufferedReader {
FileReader r = null;
// 在创建对象时将要处理的Reader传递进来
public MyBufferedReader(FileReader r) {
this.r = r;
}
// 定义自己的readLine()方法
// 抛出运行中可能会发生的异常,谁调用谁处理
public String myReadLine() throws IOException {
int num = 0;
int i = 0;
char[] cbuf = new char[4096];
while ((i=r.read()) != -1) {
// 注意'\r'代表的是一个字符
if (i == '\r')
continue;
if (i == '\n') {
// 将数据转化为String
String str = new String(cbuf, 0, num);
return str;
}
cbuf[num] = (char)i;
num ++;
}
// 如果在文档结束符所在的行中还有其他字符时,就需要把数组中的内容读出来
if (num != 0) {
String str = new String(cbuf, 0, num);
return str;
} else {
// 如果只读取了一个结束符,那就直接返回空
return null;
}
}
// 定义自己的关闭方法
// 抛出运行中可能会发生的异常,谁调用谁处理
public void myClose() throws IOException {
r.close();
}
}
使用上面定义的类
package Day19_io;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class MyBR_Apply {
public static void main(String[] args) {
String str;
FileReader fr = null;
MyBufferedReader mbr = null;
FileWriter fw = null;
BufferedWriter bw = null;
try {
fr = new FileReader("C:\\Documents and Settings\\Administrator\\桌面\\bbb.txt");
mbr = new MyBufferedReader(fr);
fw = new FileWriter("C:\\Documents and Settings\\Administrator\\桌面\\bbb1.txt");
bw = new BufferedWriter(fw);
// 调用自己的readLine()
while ((str=mbr.myReadLine()) != null) {
bw.write(str);
// 不要忘了新建一行,因为readLine()方法返回的字符串不包含任何行终止符
bw.newLine();
bw.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 处理自己的close()
if (mbr != null) {
try {
mbr.myClose();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Note:这个自定义readLine()的过程中其实采用装饰设计模式:
即在一个自定义类中,引用一个需要被装饰的类,在原有类的功能的基础上,提供加强功能。那么这个自定义类就是装饰类。
由于装饰类的作用一般是增强已有对象,所以装饰类和被装饰类通常都属于一个体系。
---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------详细请查看:http://edu.csdn.net