======Readable是java.lang里面的一个接口,它是一个字符源。阅读方法的调用能够通过CharBuffer使用Readable的字符。
======该接口只有一个方法,int read(CharBuffer cb).
======该接口是单独为Scanner创建的,以使得Scanner不必将参数局限为某个特定的类,因此,通过这种方式,Scanner不仅仅能从String,File,imputStream中读入数据,而且可以从任何继承自Readable的类中读入!
======================================来看一个程序=========================================
import java.nio.*;
import java.util.*; public class RandomWords implements Readable {
private static Random rand = new Random(47); private static final char[] capitals = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); private static final char[] lowers = "abcdefghijklmnopqrstuvwxyz".toCharArray(); private static final char[] vowels = "aeiou".toCharArray(); private int count; public RandomWords(int count) { this.count = count; } public int read(CharBuffer cb) { //这里覆盖Readable的read方法 //把判断语句放在最前面,一执行,条件就成立的话CharBuffer中没有字符,调用hasNext就会返回假 if(count-- == 0) return -1; // Indicates end of input cb.append(capitals[rand.nextInt(capitals.length)]); for(int i = 0; i < 4; i++) { cb.append(vowels[rand.nextInt(vowels.length)]); cb.append(lowers[rand.nextInt(lowers.length)]); } cb.append(" "); /*用空格来做为定界符,把CharBuffer中的字符在空格处裁开,这样子就会得到数个next()值 */ return 10; // Number of characters appended } public static void main(String[] args) { Scanner s = new Scanner(new RandomWords(10)); while(s.hasNext()) System.out.println(s.next()); } } /* Output: Yazeruyac Fowenucor Goeazimom Raeuuacio Nuoadesiw Hageaikux Ruqicibui Numasetih Kuuuuozog Waqizeyoy *///:~ 问题1:read()返回的是 int型,这个int表示什么?
-- >这个int只要不等于-1,read()就会一直被调用,直到read()抛出异常或者return -1 ! 问题1:当用Scanner.hasNext()时,是根据read的返回值来判断hasNext()的真假吗?
-- >这个程序中,hasNext()是根据CharBuffer中是否有字符串来判断真假的!与read()的返回值无关. 问题1:cb.append(" "); //这句有什么作用?
-- > 在默认的情况下,hasNext()是通过空白符来划分界限的,此句的作用就是,为CharBuffer中的字符串添加空白符! 问题1:return 10; //这里改成return 3或2等正数,为什么程序的输出结果都是一样的呢? -- >read方法的返回值只是一个标记,没有副作用(只要返回值是除-1外的任何数,不管返回的是什么数,结果都一样!),不会影响缓冲区的输出结果 ============================总结:====================================== 第一:当创建Scanner对象,并把它与Readable并联时(如Scanner s = new Scanner(new RandomWords(10));),就会自动调用Readable的read(),只要从read()方法中返回的值不是 -1
,那么就会不停的调用read(),直到从read()中返回 -1 或者 抛出异常! 第二:调用Scanner.hasNext()时,是看CharBuffer里面有没有字符,如果有就返回ture,值得注意的是,在read()里面应该添加语句:cb.append(" "); 即用空格来做为定界符,把CharBuffer中的字符在空格处裁开并做为下一次hasNext()判定字符是否为空的起始位置! |
|