练习1:
/* Modify OSExecute.java so that, instead of printing the standard output stream
* it returns the results of executing the program as a List of Strings. Demonstrate
* the use of this new version fo the utility.
*/
import java.io.*;
import java.util.*;
import static net.mindview.util.Print.*;
class OSExecuteException extends RuntimeException{
public OSExecuteException(String why){super(why);}
}
public class Ja18_22 {
public static void command(String command) {
boolean err = false;
try {
Process process =
new ProcessBuilder(command.split(" ")).start();
BufferedReader results = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String s;
LinkedList<String> ll=new LinkedList<String>();
while((s = results.readLine())!= null)
ll.add(s);
print(ll);
BufferedReader errors = new BufferedReader(
new InputStreamReader(process.getErrorStream()));
while((s = errors.readLine())!= null) {
System.err.println(s);
err = true;
}
} catch(Exception e) {
if(!command.startsWith("CMD /C"))
command("CMD /C " + command);
else
throw new RuntimeException(e);
}
if(err)
throw new OSExecuteException("Errors executing " +
command);
}
public static void main(String[] args){
command("javap Ja18_20.class");
}
} ///:~
/* Modify DirList.java (or one of it's variants) so that the FilenameFilter
* opens and reads each file (using the net.mindview.util.TextFile utility)
* and accepts the file based on whether any of the trailing arguments on the
* command line exist in that file.
* (See also, Solution DirList1b.java)
*/
import static net.mindview.util.Print.*;
import java.util.regex.*;
import java.io.*;
import java.util.*;
import net.mindview.util.*;
public class Ja18_1{
public static void main(String[] args) {
File path = new File("./abc");
String[] list;
final String[] aaa={".*\\.java","public","private"};
list = path.list(new FilenameFilter(){
private Pattern pattern=Pattern.compile(aaa[0]);
public boolean accept(File dir, String name) {
return pattern.matcher(name).matches()&&!(Collections.disjoint(Arrays.asList(aaa).subList(1, aaa.length),new TextFile(name, "\\W+")));
}
});
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
for(String dirItem : list)
System.out.println(dirItem);
System.out.println("afds");
}
}
PS: 数组String[]有大小限制,如果list太长,会溢出。
练习2:
/* Create as class called SortedDirList with a constructor that takes
* a File object and builds a sorted directory list from the files at
* that File. Add to this class two overloaded list() methods: the first
* produces the whole list, and the second produces the subset of the list
* that matches its argument (which is a regular expression).
*/
import java.util.regex.*;
import java.util.*;
import java.io.*;
import static net.mindview.util.Print.*;
class SortedDirList{
String[] ss;
public SortedDirList(File path){
ss=path.list();
Arrays.sort(ss);
}
public String[] list(){
return ss;
}
public List<String> list(String regex){
List<String> ls=new ArrayList<String>();
for(int i=0;i<ss.length;i++){
if(Pattern.compile(regex).matcher(ss[i]).matches())ls.add(ss[i]);
}
return ls;
}
}
public class Ja18_2{
public static void main(String[] args) {
SortedDirList sd=new SortedDirList(new File("."));
print(sd.list(".*\\.java"));
}
}
练习3:
// Modify DirList.java (or one of its variants) so that it
// sums up the file sizes of the selected files.
//: io/DirList.java
// Display a directory listing using regular expressions.
// {Args: "D.*\.java"}
import java.util.regex.*;
import java.io.*;
import java.util.*;
import static net.mindview.util.Print.*;
public class Ja18_3 {
public static void main(String[] args) {
File path = new File(".");
File[] list;
if(args.length == 0)
list = path.listFiles(new DirFilter(".*\\.java"));
else
list = path.listFiles(new DirFilter(args[0]));
Arrays.sort(list);
long length=0;
for(File file : list)
{
//File ff=new File(dirItem);
//System.out.println(ff.length());
length+=file.length();
}
print(length);
}
}
class DirFilter implements FilenameFilter {
private Pattern pattern;
public DirFilter(String regex) {
pattern = Pattern.compile(regex);
}
public boolean accept(File dir, String name) {
return pattern.matcher(name).matches();
}
} /* Output:
DirectoryDemo.java
DirList.java
DirList2.java
DirList3.java
*///:~
练习4:
// Use Directory.walk() to sum the sizes of all files in a directory
// tree whose names match a particular regular expression.
import net.mindview.util.*;
import static net.mindview.util.Print.*;
import java.io.*;
public class Ja18_4 {
public static void main(String[] args) {
long length=0;
for(File file:(Directory.walk(".","Ja.*\\.java").files))
length+=file.length();
print(length);
}
}
练习5:
// Modify ProcessFiles.java so that it matches a regular expression
// rather that a fixed extension.
import net.mindview.util.*;
import static net.mindview.util.Print.*;
import java.io.*;
import java.util.regex.*;
public class Ja18_5{
public interface Strategy {
void process(File file);
}
private Strategy strategy;
private String ext;
public Ja18_5(Strategy strategy, String ext) {
this.strategy = strategy;
this.ext = ext;
}
public void start(String[] args) {
try {
if(args.length == 0)
processDirectoryTree(new File("."));
else
for(String arg : args) {
File fileArg = new File(arg);
if(fileArg.isDirectory())
processDirectoryTree(fileArg);
else {
// Allow user to leave off extension:
if(Pattern.compile(ext).matcher(arg).matches())
strategy.process(new File(arg).getCanonicalFile());
}
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public void
processDirectoryTree(File root) throws IOException {
for(File file : Directory.walk(
root.getAbsolutePath(), ext))
strategy.process(file.getCanonicalFile());
}
// Demonstration of how to use it:
public static void main(String[] args) {
new Ja18_5(new Ja18_5.Strategy() {
public void process(File file) {
System.out.println(file);
}
}, ".*\\.java").start(args);
}
} /* (Execute to see output) *///:~
练习6:
/* Use ProcessFiles to find all the Java source-source code files in
* a particular directory subtree that have been modified after a
* particular date.
*/
import java.io.*;
import net.mindview.util.*;
import static net.mindview.util.Print.*;
import java.util.*;
import java.text.*;
public class Ja18_6{
public static void main(String[] args){
String[] a={"."};
final SimpleDateFormat sdf=new SimpleDateFormat("MM/dd/yyyy");
new ProcessFiles(new ProcessFiles.Strategy(){
public void process(File file){
Date da=new Date(file.lastModified());
try{
if(da.after(sdf.parse("04/23/2018")))print(file);
}catch(Exception e){
}
}
},"java").start(a);
}
}
PS: 日期格式上,很有参考价值!
练习7:
/* Open a text file so that you can read the file one line at a time. Read
* each line as a String and place that String object into a LinkedList.
* Print all of the lines in the LinkedList in reverse order.
*/
import java.util.*;
import static net.mindview.util.Print.*;
import java.io.*;
public class Ja18_7{
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new FileReader("Ja18_5.java"));
StringBuilder sb=new StringBuilder();
LinkedList<String> ll=new LinkedList<String>();
String s;
while((s=br.readLine())!=null)ll.add(s);
br.close();
print(ll);
}
}
练习8:
// Modify Exercise 7 so that the name of the file you read is provided as a
// command-line argument.
import java.util.*;
import static net.mindview.util.Print.*;
import java.io.*;
public class Ja18_8{
public static void main(String[] args) throws IOException{
if(args.length==0)System.exit(0);
BufferedReader br=new BufferedReader(new FileReader(args[0]));
StringBuilder sb=new StringBuilder();
LinkedList<String> ll=new LinkedList<String>();
String s;
while((s=br.readLine())!=null)ll.add(s);
br.close();
print(ll);
}
}
练习9:
// Modify Exercise 8 to force all the lines in the LinkedList to uppercase
// and send the results to System.out.
import java.util.*;
import static net.mindview.util.Print.*;
import java.io.*;
public class Ja18_9{
public static void main(String[] args) throws IOException{
if(args.length==0)System.exit(0);
BufferedReader br=new BufferedReader(new FileReader(args[0]));
StringBuilder sb=new StringBuilder();
LinkedList<String> ll=new LinkedList<String>();
String s;
while((s=br.readLine())!=null)ll.add(s.toUpperCase());
br.close();
print(ll);
}
}
练习10:
// Modify Exercise 8 to take additional command-line arguments of words to
// find in the file. Print all lines in which any of the words match.
import java.util.*;
import static net.mindview.util.Print.*;
import java.io.*;
public class Ja18_10{
public static void main(String[] args) throws IOException{
if(args.length<2)System.exit(0);
BufferedReader br=new BufferedReader(new FileReader(args[0]));
StringBuilder sb=new StringBuilder();
LinkedList<String> ll=new LinkedList<String>();
String s;
ArrayList<String> line=new ArrayList<String>(Arrays.asList(args).subList(1,args.length-1));
while((s=br.readLine())!=null)if(!Collections.disjoint(line,Arrays.asList(s.split("\\W+"))))ll.add(s);
br.close();
print(ll);
}
}
练习11:
/* In the innerclasses/GreenhouseController.java example, GreenhouseController
* contains a hard-coded set of events. Change the program so that it reads the
* events from a text file.
*/
import static net.mindview.util.Print.*;
import java.io.*;
import innerclasses.controller.*;
import innerclasses.*;
import java.util.*;
public class Ja18_11 {
// To read events from text file and add to HashMap<String,Long>:
public static Map<String,Long> readEvents(String filename)
throws IOException {
BufferedReader in = new BufferedReader(new FileReader(filename));
String s;
Map<String,Long> map = new HashMap<String,Long>();
while((s = in.readLine()) != null) {
String [] sa = s.split("[()]");
print(Arrays.asList(sa));
map.put(sa[0], new Long(sa[1]));
}
in.close();
return map;
}
// To build Event objects from Map.Entry objects:
private static Event makeEvent(GreenhouseControls gc, Map.Entry<String,Long> me) {
String key = me.getKey().trim();
print(key);
Long value = me.getValue();
print(value);
if(key.equals("Bell")) return gc.new Bell(value);
if(key.equals("LightOn")) return gc.new LightOn(value);
if(key.equals("LightOff")) return gc.new LightOff(value);
if(key.equals("WaterOn")) return gc.new WaterOn(value);
if(key.equals("WaterOff")) return gc.new WaterOff(value);
if(key.equals("ThermostatDay")) return gc.new ThermostatDay(value);
if(key.equals("ThermostatNight")) return gc.new ThermostatNight(value);
return null;
}
public static void main(String[] args) {
GreenhouseControls gc = new GreenhouseControls();
// Instead of hard-wiring, you could parse
// configuration information from a text file here:
try {
// Read text and convert lines to map entries:
Map<String,Long> map = readEvents("EventList.txt");
Event[] eventList = new Event[map.size()];
int i = 0;
// Make events from map and add to Event array:
for(Map.Entry<String,Long> me : map.entrySet()) {
eventList[i++] = makeEvent(gc, me);
}
print(Arrays.asList(eventList));
gc.addEvent(gc.new Restart(2000, eventList));
if(args.length != 1) {
System.out.println("Usage: enter integer terminate time");
System.exit(0);
}
if(args.length == 1)
gc.addEvent(new GreenhouseControls.Terminate(
new Integer(args[0])));
gc.run();
} catch(IOException e) {
System.out.println(e);
}
}
}
//PS:有时候trim()必不可少
PS:有时候trim()必不可少
练习12:
/* Modify Exercise 8 to also open a text file so you can write text into it.
* Write the lines in the LinkedList, along with line numbers (do not attempt
* to use the "LineNumber" classes), out to the file.
*/
import java.util.*;
import static net.mindview.util.Print.*;
import java.io.*;
public class Ja18_12{
public static void main(String[] args) throws IOException{
if(args.length==0)System.exit(0);
BufferedReader br=new BufferedReader(new FileReader(args[0]));
LinkedList<String> ll=new LinkedList<String>();
String s;
while((s=br.readLine())!=null)ll.add(s);
PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter("Ja18_12.test")));
Iterator<String> it=ll.iterator();
int i=0;
while(it.hasNext()){
String ss=it.next();
print(ss);
pw.println(i++ +":" + ss);
}
pw.close();
}
}
PS: PrintWriter must have close()!! //BufferedWriter 却没有强调
练习13:
/* Modify BasicFileOutput.java so that it uses LineNumberReader to keep
* track of the line count. Note that it's much easier to just keep track
* programmatically.
*/
import java.io.*;
import static net.mindview.util.Print.*;
import io.*;
public class Ja18_13 {
static String file = "Ja18_13.test";
public static void main(String[] args)
throws IOException {
LineNumberReader in = new LineNumberReader(
new StringReader(
BufferedInputFile.read("Ja18_12.java")));
PrintWriter out = new PrintWriter(
new BufferedWriter(new FileWriter(file)));
int lineCount = 1;
String s;
print(in.getLineNumber());
while((s = in.readLine()) != null )
out.println(in.getLineNumber()-1 + ": " + s);
out.close();
// Show the stored file:
System.out.println(BufferedInputFile.read(file));
}
}
练习14:
// Starting with BasicFileOutput.java, write a program that compares the
// performance of writing to a file when using buffered and unbuffered I/O.
//: io/BasicFileOutput.java
import static net.mindview.util.Print.*;
import java.io.*;
import io.*;
public class Ja18_14 {
static String file = "Ja18_14.out";
public static void main(String[] args)
throws IOException {
BufferedReader in = new BufferedReader( new StringReader( BufferedInputFile.read("Ja18_13.java")));
PrintWriter out = new PrintWriter( new BufferedWriter(new FileWriter(file)));
PrintWriter out2 = new PrintWriter( (new FileWriter(file)));
int lineCount = 1;
String s;
long start=System.nanoTime();
while((s = in.readLine()) != null )
out.println(lineCount++ + ": " + s);
out.close();
long end=System.nanoTime();
print("11111,:"+(start-end));
start=System.nanoTime();
lineCount=0;
while((s = in.readLine()) != null )
out2.println(lineCount++ + ": " + s);
out2.close();
end=System.nanoTime();
print("22222,:"+(start-end));
// Show the stored file:
System.out.println(BufferedInputFile.read(file));
}
}
PS:没有缓冲速度更快?
练习15:
/* Look up DataOutputStream and DataInputStream in the JDK documentation.
* Starting with StoringAndRecoveringData.java, create a program that stores
* and then retrieves all the different possible types provided by the
* DataOutputStream and DataInputStream classes. Verify that the values
* are stored and retrieved correctly.
*/
import java.io.*;
import static net.mindview.util.Print.*;
public class Ja18_15 {
public static void main(String[] args) throws IOException {
DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream("Ja18_15.test")));
print("Initial out.size() = " + out.size());
byte[] ba = {0,1,2,3};
// Store first 3 bytes of byte[] ba:
out.write(ba,0,3);
// Store all 4 bytes in byte[] ba:
out.write(ba);
out.write((int)255); // Stores the lower 8 bits of int
out.writeBoolean(true);
out.writeByte((int)1000000);
out.writeBytes((String)"hi");
out.writeChar(120);
out.writeChars("hi");
out.writeDouble(3.14159);
out.writeFloat(2.1f);
out.writeInt(1057);
out.writeLong(123456789L);
out.writeShort(123);
out.writeUTF("Nice piece of work");
print("After writing, out.size() = " + out.size());
out.close();
print("Reading:");
DataInputStream in = new DataInputStream(
new BufferedInputStream(
new FileInputStream("Ja18_15.test")));
byte[] baIn = new byte[3];
print("bytes read by in.read(baIn, 0, 3) = " + in.read(baIn, 0, 3));
print("baIn = ");
for(int i = 0; i < baIn.length; i++)
print(baIn[i] + " ");
print();
// Read next 4 bytes as int:
print("in.readInt() = " + in.readInt());
print("in.read() = " + in.read());
print("in.readBoolean() = " + in.readBoolean());
print("in.readByte() = " + in.readByte());
print("in.read() = " + in.read()); // ASCII h = 104
print("in.read() = " + in.read()); // ASCII i = 105
print("in.readChar() = " + in.readChar());
print("in.readChar() = " + in.readChar());
print("in.readChar() = " + in.readChar());
print("in.readDouble() = " + in.readDouble());
print("in.readFloat() = " + in.readFloat());
print("in.readInt() = " + in.readInt());
print("in.readLong() = " + in.readLong());
print("in.readShort() = " + in.readShort());
print("in.readUTF() = " + in.readUTF());
}
}
PS:文件中只有writeUTF的内容不是乱码
练习16:
/* Look up RandomAccessFile in the JDK documentation. Starting with
* UsingRandomAccessFile.java, create a program that stores and then
* retrieves all the different possible types provided by the
* RandomAccessFile class. Verify that the values are stored and
* retrieved properly.
*/
import java.io.*;
import static net.mindview.util.Print.*;
public class Ja18_16 {
public static void main(String[] args) throws IOException {
RandomAccessFile rf=new RandomAccessFile("Ja18_15.test","rw");
rf.writeDouble(1434);
rf.writeUTF("fd");
rf.writeChars("erw");
rf.close();
RandomAccessFile rf2=new RandomAccessFile("Ja18_15.test","r");
rf2.seek(8);
print(rf2.readUTF());
print(rf2.readChar());
}
}
练习17:
/* Using TextFile and a Map<Character,Integer>, create a program that counts
* the occurrence of all the different characters in a file. (So if there are
* 12 occurrences of the letter 'a' in the file, the Integer associated with
* the Character containing 'a' in the Map contains '12').
*/
import java.io.*;
import static net.mindview.util.Print.*;
import net.mindview.util.*;
import java.util.*;
import java.util.regex.*;
public class Ja18_17 {
public static void main(String[] args) throws IOException {
ArrayList<String> al=new TextFile("Ja18_16.java","");
Iterator<String> it=al.iterator();
String s;
Map<String,Integer> map=new HashMap<String,Integer>();
Integer i=0;
while(it.hasNext()){
s=it.next();
if(Pattern.compile("\\w").matcher(s).matches()){
if((i=map.get(s))==null)map.put(s,1);
else map.put(s,i+1);
}
}
print(map);
}
}
练习18:
// Modify Ja18_18.java so that it passes IOExceptions out to the caller.
import java.io.*;
import java.util.*;
import net.mindview.util.*;
public class Ja18_18 extends ArrayList<String> {
// Read a file as a single string:
public static String read(String fileName) throws IOException{
StringBuilder sb = new StringBuilder();
BufferedReader in= new BufferedReader(new FileReader(
new File(fileName).getAbsoluteFile()));
try {
String s;
while((s = in.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} finally {
in.close();
}
return sb.toString();
}
// Write a single file in one method call:
public static void write(String fileName, String text) throws IOException {
PrintWriter out = new PrintWriter(
new File(fileName).getAbsoluteFile());
try {
out.print(text);
} finally {
out.close();
}
}
// Read a file, split by any regular expression:
public Ja18_18(String fileName, String splitter) throws IOException{
super(Arrays.asList(read(fileName).split(splitter)));
// Regular expression split() often leaves an empty
// String at the first position:
if(get(0).equals("")) remove(0);
}
// Normally read by lines:
public Ja18_18(String fileName) throws IOException{
this(fileName, "\n");
}
public void write(String fileName) throws IOException {
PrintWriter out = new PrintWriter(
new File(fileName).getAbsoluteFile());
try {
for(String item : this)
out.println(item);
} finally {
out.close();
}
}
// Simple test:
public static void main(String[] args) throws IOException{
String file = read("Ja18_18.java");
write("test.txt", file);
Ja18_18 text = new Ja18_18("test.txt");
text.write("test2.txt");
// Break into unique sorted list of words:
TreeSet<String> words = new TreeSet<String>(
new Ja18_18("Ja18_18.java", "\\W+"));
// Display the capitalized words:
System.out.println(words.headSet("a"));
}
}
练习19:
// Using BinaryFile and a Map<Byte,Integer>, create a program that
// counts the occurrence of all the different bytes in a file.
import java.io.*;
import static net.mindview.util.Print.*;
import net.mindview.util.*;
import java.util.*;
import java.util.regex.*;
public class Ja18_19 {
public static void main(String[] args) throws IOException {
BufferedInputStream bf=new BufferedInputStream(new FileInputStream(new File("Ja18_18.class")));
byte[] datas=new byte[bf.available()];
bf.read(datas);
Map<Byte,Integer> map=new HashMap<Byte,Integer>();
for(byte data:datas){
if(map.containsKey(data))map.put((Byte)data,map.get(data)+1);
else map.put((Byte)data,1);
}
print(map);
}
}
练习20:
// Using Directory.walk() and BinaryFile, verify that all .class files
// in a directory tree begin with the hex characters 'CAFEBABE'.
import java.io.*;
import static net.mindview.util.Print.*;
import net.mindview.util.*;
import java.util.*;
import java.util.regex.*;
public class Ja18_20 {
public static void main(String[] args) throws IOException {
int flag=1;
for(File f:Directory.walk(".",".*\\.class")){
BufferedInputStream bf=new BufferedInputStream(new FileInputStream(f));
byte[] datas=new byte[bf.available()];
bf.read(datas);
print(Integer.toHexString(datas[0] & 0xff).toUpperCase()+Integer.toHexString(datas[1] & 0xff).toUpperCase()+Integer.toHexString(datas[2] & 0xff).toUpperCase()+Integer.toHexString(datas[3] & 0xff).toUpperCase());
}
}
}
练习21:
/* Write a program that takes standard input and capitalizes all
* characters, then puts the results on standard output. Redirect
* the contents of a file into this program (the process of redirection
* will vary dependign on your operating system).
*/
import java.io.*;
public class Ja18_21{
public static void main(String[] args) throws IOException {
File file = new File("Ja18_20.java");
BufferedInputStream inFile =
new BufferedInputStream(new
FileInputStream(file));
System.setIn(inFile);
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
String s;
while((s = stdin.readLine()) != null)
System.out.println(s.toUpperCase());
}
}
练习22:
/* Modify OSExecute.java so that, instead of printing the standard output stream
* it returns the results of executing the program as a List of Strings. Demonstrate
* the use of this new version fo the utility.
*/
import java.io.*;
import java.util.*;
import static net.mindview.util.Print.*;
class OSExecuteException extends RuntimeException{
public OSExecuteException(String why){super(why);}
}
public class Ja18_22 {
public static void command(String command) {
boolean err = false;
try {
Process process =
new ProcessBuilder(command.split(" ")).start();
BufferedReader results = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String s;
LinkedList<String> ll=new LinkedList<String>();
while((s = results.readLine())!= null)
ll.add(s);
print(ll);
BufferedReader errors = new BufferedReader(
new InputStreamReader(process.getErrorStream()));
while((s = errors.readLine())!= null) {
System.err.println(s);
err = true;
}
} catch(Exception e) {
if(!command.startsWith("CMD /C"))
command("CMD /C " + command);
else
throw new RuntimeException(e);
}
if(err)
throw new OSExecuteException("Errors executing " +
command);
}
public static void main(String[] args){
command("javap Ja18_20.class");
}
} ///:~
练习23:
// Create and test a utility to print the contents of a CharBuffer
// up to the point where the characters are no longer printable.
import java.nio.*;
import static net.mindview.util.Print.*;
public class Ja18_23{
public static boolean isPrintable(char c) {
// Check char in printable range:
return (((c >= '!') && (c <= '~')) ? true : false);
}
public static void printCharBuffer(CharBuffer cb) {
cb.clear(); // Sets position to zero, limit to capacity
while(cb.hasRemaining()) {
char c = cb.get();
if(isPrintable(c)) System.out.print(c);
}
}
public static void main(String[] args) throws Exception {
char[] ca = {'w','x','y','z'};
CharBuffer cb = CharBuffer.wrap(ca);
print("CharBuffer by wrapping char[]: ");
printCharBuffer(cb);
print();
CharBuffer cb2 = CharBuffer.allocate(6);
char[] ca2 = {'s','t','u','v','w'};
cb2.put(ca2);
print("CharBuffer by allocation: ");
printCharBuffer(cb2);
print();
// Try some unprintable chars:
char[] ca3 = {(char)0x01, (char)0x07, (char)0x7F,'b','y','e'};
CharBuffer cb3 = CharBuffer.wrap(ca3);
print("CharBuffer including some unprintables: ");
printCharBuffer(cb3);
}
}
练习24:
// Modify IntBufferDemo.java to use doubles.
// Manipulating ints in a ByteBuffer with a DoubleBuffer
import java.nio.*;
public class Ja18_24 {
private static final int BSIZE = 1024;
public static void main(String[] args) {
ByteBuffer bb = ByteBuffer.allocate(BSIZE);
DoubleBuffer ib = bb.asDoubleBuffer();
// Store an array of int:
ib.put(new double[]{ 11, 42, 47, 99, 143, 811, 1016 });
// Absolute location read and write:
System.out.println(ib.get(3));
ib.put(3, 1811);
// Setting a new limit before rewinding the buffer.
ib.flip();
while(ib.hasRemaining()) {
double i = ib.get();
System.out.println(i);
}
}
}
练习25:
/* Experiment with changing the ByteBuffer.allocate() statements
* in the examples in this chapter to ByteBuffer.allocateDirect().
* Demonstrate performance differences, but also notice whether
* the startup time of the programs noticeably changes.
*/
import static net.mindview.util.Print.*;
import java.nio.*;
abstract class Tester{
private String name;
public Tester(String name){this.name=name;}
public void runTest(){
long start=System.nanoTime();
test();
long end=System.nanoTime();
print(name+": "+(end-start));
}
public abstract void test();
static Tester[] tests={
new Tester("withDirect"){
public void test() {
ByteBuffer bb=ByteBuffer.allocateDirect(32);
IntBuffer ib=bb.asIntBuffer();
for(int i=0;i<8;i++){
ib.put(i);
}
}
},
new Tester("withoutDirect"){
public void test() {
ByteBuffer bb=ByteBuffer.allocate(32);
IntBuffer ib=bb.asIntBuffer();
for(int i=0;i<8;i++){
ib.put(i);
}
}
}
};
}
public class Ja18_25{
public static void main(String[] args){
for(Tester test:Tester.tests){
test.runTest();
}
}
}
练习26:
// Modify strings/JGrep.java to use java.nio memory mapped files.
import java.util.regex.*;
import static net.mindview.util.Print.*;
import java.util.*;
import net.mindview.util.*;
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.charset.*;
public class Ja18_26 {
public static void main(String[] args) throws Exception {
if(args.length < 2) {
System.out.println("Usage: java JGrep file regex");
System.exit(0);
}
Pattern p = Pattern.compile(args[1]);
// Iterate through the lines of the input file:
int index = 0;
Matcher m = p.matcher("");
FileChannel fc=new FileInputStream(new File(args[0])).getChannel();
MappedByteBuffer in=fc.map(FileChannel.MapMode.READ_ONLY,0,fc.size());
String[] sa=Charset.forName(System.getProperty("file.encoding")).decode(in).toString().split("\n");
print(Arrays.toString(sa));
for(String line : sa) {
m.reset(line);
while(m.find())
System.out.println(index++ + ": " +
m.group() + ": " + m.start());
}
fc.close();
}
}
练习27:
/* Create a Serializable class containing a reference to an object of a
* second Serializable class. Create an instance of your class, serialize it
* to disk, then restore it and verify that the process worked correctly.
*/
import java.io.*;
import static net.mindview.util.Print.*;
import java.util.*;
class A implements Serializable{
private B b=new B();
public String toString(){
return ("it's A; "+b);
}
}
class B implements Serializable{
public String toString(){
return ("it's B");
}
}
public class Ja18_27{
public static void main(String[] args) throws IOException,ClassNotFoundException,FileNotFoundException{
A a=new A();
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("Ja18_27.out"));
oos.writeObject(a);
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("Ja18_27.out"));
A aa=(A)ois.readObject();
print(aa);
}
}
练习28:
/* In Blips.java, copy the file and rename it to BlipCheck.java and
* rename the class Blip2 to BlipCheck (making it public and removing
* the public scope from the class Blips in the process). Remove the
* //! marks in the file and execute the program, including the offending
* lines. Next, comment out the default constructor for BlipCheck. Run
* it and explain why it works. Note that after compiling, you must
* execute the program with "java Blips" because the main() methon is
* still in the class Blips.
*/
import java.io.*;
import static net.mindview.util.Print.*;
class Blip1 implements Externalizable {
public Blip1() {
print("Blip1 Constructor");
}
public void writeExternal(ObjectOutput out)
throws IOException {
print("Blip1.writeExternal");
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
print("Blip1.readExternal");
}
}
public class Ja18_28 implements Externalizable {
/*Ja18_28() {
print("Ja18_28 Constructor");
}*/
public void writeExternal(ObjectOutput out)
throws IOException {
print("Ja18_28.writeExternal");
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
print("Ja18_28.readExternal");
}
}
class Blips {
public static void main(String[] args)
throws IOException, ClassNotFoundException {
print("Constructing objects:");
Blip1 b1 = new Blip1();
Ja18_28 b2 = new Ja18_28();
ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("Blips.out"));
print("Saving objects:");
o.writeObject(b1);
o.writeObject(b2);
o.close();
// Now get them back:
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Blips.out"));
print("Recovering b1:");
b1 = (Blip1)in.readObject();
// OOPS! Throws an exception:
print("Recovering b2:");
b2 = (Ja18_28)in.readObject();
}
}
练习29:
// In Blip29.java, comment out the two lines after the phrases "You must
// do this:" and run the program. Explain the result and why it differs
// from when the two lines are in the program.
//: io/Ja18_29.java
// Reconstructing an externalizable object.
import java.io.*;
import static net.mindview.util.Print.*;
public class Ja18_29 implements Externalizable {
private int i;
private String s; // No initialization
public Ja18_29() {
print("Ja18_29 Constructor");
// s, i not initialized
}
public Ja18_29(String x, int a) {
print("Ja18_29(String x, int a)");
s = x;
i = a;
// s & i initialized only in non-default constructor.
}
public String toString() { return s + i; }
public void writeExternal(ObjectOutput out)
throws IOException {
print("Ja18_29.writeExternal");
// You must do this:
//out.writeObject(s);
//out.writeInt(i);
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
print("Ja18_29.readExternal");
// You must do this:
//s = (String)in.readObject();
//i = in.readInt();
}
public static void main(String[] args)
throws IOException, ClassNotFoundException {
print("Constructing objects:");
Ja18_29 b3 = new Ja18_29("A String ", 47);
print(b3);
ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("Ja18_29.out"));
print("Saving object:");
o.writeObject(b3);
o.close();
// Now get it back:
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Ja18_29.out"));
print("Recovering b3:");
b3 = (Ja18_29)in.readObject();
print(b3);
}
}
练习30:
// Repair the program CADState.java as described in the text.
import java.io.*;
import static net.mindview.util.Print.*;
import java.util.*;
abstract class Shape implements Serializable {
public static final int RED = 1, BLUE = 2, GREEN = 3;
private int xPos, yPos, dimension;
private static Random rand = new Random(47);
private static int counter = 0;
public abstract void setColor(int newColor);
public abstract int getColor();
public Shape(int xVal, int yVal, int dim) {
xPos = xVal;
yPos = yVal;
dimension = dim;
}
public String toString() {
return getClass() +
"color[" + getColor() + "] xPos[" + xPos +
"] yPos[" + yPos + "] dim[" + dimension + "]\n";
}
public static Shape randomFactory() {
int xVal = rand.nextInt(100);
int yVal = rand.nextInt(100);
int dim = rand.nextInt(100);
switch(counter++ % 3) {
default:
case 0: return new Circle(xVal, yVal, dim);
case 1: return new Square(xVal, yVal, dim);
case 2: return new Line(xVal, yVal, dim);
}
}
}
class Circle extends Shape {
private static int color = RED;
public Circle(int xVal, int yVal, int dim) {
super(xVal, yVal, dim);
}
public void setColor(int newColor) { color = newColor; }
public int getColor() { return color; }
public static void serializeStaticState(ObjectOutputStream os) throws IOException { os.writeInt(color); }
public static void deserializeStaticState(ObjectInputStream os) throws IOException { color = os.readInt();print(color); }
}
class Square extends Shape {
private static int color;
public Square(int xVal, int yVal, int dim) {
super(xVal, yVal, dim);
color = RED;
}
public void setColor(int newColor) { color = newColor; }
public int getColor() { return color; }
public static void serializeStaticState(ObjectOutputStream os) throws IOException { os.writeInt(color); }
public static void deserializeStaticState(ObjectInputStream os) throws IOException { color = os.readInt(); print(color);}
}
class Line extends Shape {
private static int color = RED;
public static void serializeStaticState(ObjectOutputStream os) throws IOException { os.writeInt(color); }
public static void deserializeStaticState(ObjectInputStream os) throws IOException { color = os.readInt(); print(color);}
public Line(int xVal, int yVal, int dim) {
super(xVal, yVal, dim);
}
public void setColor(int newColor) { color = newColor; }
public int getColor() { return color; }
}
public class Ja18_30 {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
List<Shape> shapes = new ArrayList<Shape>();
// Make some shapes:
for(int i = 0; i < 10; i++)
shapes.add(Shape.randomFactory());
// Set all the static colors to GREEN:
for(int i = 0; i < 10; i++)
((Shape)shapes.get(i)).setColor(Shape.GREEN);
// Save the state vector:
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("CADState.out"));
Circle.serializeStaticState(out);
Square.serializeStaticState(out);
Line.serializeStaticState(out);
out.writeObject(shapes);
// Display the shapes:
System.out.println(shapes);
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("CADState.out"));
// Read in the same order they were written:
Circle.deserializeStaticState(in);
Square.deserializeStaticState(in);
Line.deserializeStaticState(in);
List<Shape> shapes2 = (List<Shape>)in.readObject();
System.out.println(shapes2);
}
}
练习31:
练习32:
练习33:
// Write a program that displays the current value of a directory called
// "base directory" and prompts you for a new value. Use the Preferences API
// to store the value.
import java.util.prefs.*;
import static net.mindview.util.Print.*;
public class Ja18_33{
public static void main(String[] args) throws Exception{
Preferences prefs=Preferences.userNodeForPackage(Ja18_33.class);
int pp=prefs.getInt("base directory",0);
prefs.putInt("base directory",5);
for(String key:prefs.keys())print(prefs.get(key,null));
print(prefs.getInt("base directory",5));
}
}