Java Scanner Readable
Posted 飞龙dragon
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Scanner Readable相关的知识,希望对你有一定的参考价值。
通过implements(实现)Readbale interface(接口)的 read() method(方法) 实现自己添加字符到buffer里,然后读取
package object; //: interfaces/RandomWords.java // Implementing an interface to conform to a method. 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) { //read()方法来自Readable接口,Sanner()里也有用到 if(count-- == 0) return -1; // Indicates end of input cb.append(capitals[rand.nextInt(capitals.length)]); //从cpitals里面每次读出一个字符并添加到buffer里面 for(int i = 0; i < 4; i++) { cb.append(vowels[rand.nextInt(vowels.length)]);//从vowels里面每次读出four char 字符并添加到buffer里面 cb.append(lowers[rand.nextInt(lowers.length)]);//append()方法:添加字符到buffer里面 } cb.append(" "); //空格和‘ ‘功能一样 return 10; // Number of characters appended } public static void main(String[] args) { Scanner s = new Scanner(new RandomWords(10));
// new RandomWords(10)可以换做任意实现了Readable接口的类所生成的对象 while(s.hasNext()) //hasNext()通过调用readInput()方法调用read()方法知道read()返回-1结束 System.out.println(s.next()); } } /* Output: Yazeruyac Fowenucor Goeazimom Raeuuacio Nuoadesiw Hageaikux Ruqicibui Numasetih Kuuuuozog Waqizeyoy *///:~
以上是关于Java Scanner Readable的主要内容,如果未能解决你的问题,请参考以下文章
java.lang.SecurityException:不再支持 MODE_WORLD_READABLE
13.Java中Comparable接口,Readable接口和Iterable接口