本帖最后由 早知道 于 2013-9-20 20:14 编辑
代码如下:
public class MyBufferedReader {
public FileReader reader = null;
public MyBufferedReader(FileReader reader){
this.reader = reader;
}
public String myReadLine() throws IOException{//定义要功能抛出异常
StringBuilder sb = new StringBuilder();
char b = 0;
while((b= (char) reader.read())!=-1){
if(b=='\r')
continue;
if(b=='\n')
return sb.toString();
else{
sb.append((char)b);//栈溢出
}
}
if(sb.length()!=0)
return sb.toString();
return null;
}
public void Myclose() throws IOException {
reader.close();
}
}
class MyBufferedTest{
public static void main(String[] args){
MyBufferedReader buf = null;
try {
buf = new MyBufferedReader(new FileReader("buf.txt"));
String len = null;
while((len=buf.myReadLine())!=null){
System.out.println(len);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(buf!=null)
buf.Myclose();
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException("读取关闭失败");
}
}
}
}
报错:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2882)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:100)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:572)
at java.lang.StringBuilder.append(StringBuilder.java:203)
at cn.itcast.io.MyBufferedReader.myReadLine(MyBufferedReader.java:22)
at cn.itcast.io.MyBufferedTest.main(MyBufferedReader.java:45)
|