本帖最后由 Up↑Lee↗ 于 2014-4-2 20:50 编辑
有两段代码,有一段代码用到另外一段代码中的类。怎么办??我试着把代码 1 放在一个包中,然后在代码2中进行导包,为什么操作失败??
代码1:- package pack1; //自己加的
- import java.io.*;
- class MyBufferedReader extends Reader
- {
-
- private Reader r;
- MyBufferedReader(Reader r)
- {
- this.r = r;
- }
- //可以一次读一行数据的方法。
- public String myReadLine()throws IOException
- {
- //定义一个临时容器。原BufferReader封装的是字符数组。
- //为了演示方便。定义一个StringBuilder容器。因为最终还是要将数据变成字符串。
- StringBuilder sb = new StringBuilder();
- int ch = 0;
- while((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;
- }
- /*
- 覆盖Reader类中的抽象方法。
- */
- public int read(char[] cbuf, int off, int len) throws IOException
- {
- return r.read(cbuf,off,len) ;
- }
- public void close()throws IOException
- {
- r.close();
- }
- public void myClose()throws IOException
- {
- r.close();
- }
- }
- class MyBufferedReaderDemo
- {
- public static void main(String[] args) throws IOException
- {
- FileReader fr = new FileReader("buf.txt");
- MyBufferedReader myBuf = new MyBufferedReader(fr);
- String line = null;
- while((line=myBuf.myReadLine())!=null)
- {
- System.out.println(line);
- }
- myBuf.myClose();
- }
- }
复制代码 代码2:
- import pack1.*; //自己加的
- import java.io.*;
- class MyLineNumberReader extends MyBufferedReader
- {
- private int lineNumber;
- MyLineNumberReader(Reader r)
- {
- super(r);
- }
- public String myReadLine()throws IOException
- {
- lineNumber++;
- return super.myReadLine();
- }
- public void setLineNumber(int lineNumber)
- {
- this.lineNumber = lineNumber;
- }
- public int getLineNumber()
- {
- return lineNumber;
- }
- }
- /*
- class MyLineNumberReader
- {
- private Reader r;
- private int lineNumber;
- MyLineNumberReader(Reader r)
- {
- this.r = r;
- }
- public String myReadLine()throws IOException
- {
- lineNumber++;
- StringBuilder sb = new StringBuilder();
- int ch = 0;
- while((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 void setLineNumber(int lineNumber)
- {
- this.lineNumber = lineNumber;
- }
- public int getLineNumber()
- {
- return lineNumber;
- }
- public void myClose()throws IOException
- {
- r.close();
- }
- }
- */
- class MyLineNumberReaderDemo
- {
- public static void main(String[] args) throws IOException
- {
- FileReader fr = new FileReader("BufferedWriterDemo.java");
- MyLineNumberReader mylnr = new MyLineNumberReader(fr);
- String line = null;
- mylnr.setLineNumber(100);
- while((line=mylnr.myReadLine())!=null)
- {
- System.out.println(mylnr.getLineNumber()+"::"+line);
- }
- mylnr.myClose();
- }
- }
复制代码
|