/* 需求:根据readLine方法原理,模拟BufferedReader写一个自己的MyBufferedReader
*/
import java.io.*;
class MyBufferedReader extends Reader
{
private Reader r;//定义接收的流对象
MyBufferedReader(Reader r)
{
this.r=r;
}
//自定义整行读取
public String myReadline() throws IOException
{
//创建一个容器,用来存储一行的字符
StringBuilder sb = new StringBuilder();
//一个字符一个字符读取
for (int ch=0;(ch=r.read())!=-1 ; )
{
if (ch=='\r')//如果遇到换行符,则据继续
continue;
if (ch=='\n')//如果遇到回车符,表示该行读取完毕
return sb.toString();
else
sb.append((char)ch);//将该行的字符添加到容器
}
if(sb.length()!=0)//如果读取结束,容器中还有字符,则返回元素
return sb.toString();
return null;
}
//复写父类中的抽象方法
public int read(char[] cbuf,int off,int len) throws IOException
{
return r.read(cbuf,off,len);
}
//复写父类的close方法
public void close()throws IOException
{
r.close();
}
}
//测试MyBufferedReader
class MyBufferedReaderDemo
{
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("copy.txt");
MyBufferedReader myBuf = new MyBufferedReader(fr);
String line = null;
while ((line=myBuf.myReadline())!=null)
{
System.out.println(line);//显示效果
}
myBuf.close();
/*
MyBufferedReader mbr = null;
try
{
mbr = new MyBufferedReader(new FileReader("copy.txt"));//创建缓冲读对象
for (String line=null;(line=mbr.myReadline())!=null ; )
{
System.out.println(line);//显示效果
}
}
catch (IOException e)
{
throw new RuntimeException("读失败");
}
finally
{
try
{
if(mbr!=null)
mbr.close();
}
catch (IOException e)
{
throw new RuntimeException("读取流失败");
}
}
*/
}
}
编译可以通过,就是运行 让我有点纳闷,我的环境变量那些也没问题啊
E:\java1120\day19>javac MyBufferedReaderDemo.java
E:\java1120\day19>java MybufferedReaderDemo
Exception in thread "main" java.lang.NoClassDefFoundError: MybufferedReaderDemo
(wrong name: MyBufferedReaderDemo)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:12
4)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
Could not find the main class: MybufferedReaderDemo. Program will exit.
|
-
3.png
(12.04 KB, 下载次数: 15)
|