think in java第18章Java i/o系统课后习题,java第18章
分享于 点击 36909 次 点评:107
think in java第18章Java i/o系统课后习题,java第18章
练习1
searchWords(final String[] arr)的参数arr列表中,第一个参数表示文件扩展名,其他参数为要搜索的words,只要包含其中一个word,就通过
// : io/E01_SearchWords.java
package exercise.io;
import java.io.*;
import java.util.*;
import net.mindview.util.TextFile;
public class E01_SearchWords
{
public static void main(String[] args)
{
String[] arr = {"java", "BinaryFile"};
searchWords(arr);
}
public static void searchWords(final String[] arr)
{
File path = new File("src/net/mindview/util");
String[] list;
if (arr.length == 0)
{
list = path.list();
}
else
{
list = path.list(new FilenameFilter()
{
private String ext = arr[0].toLowerCase();
// accept方法是被list方法调用的,用来过滤每一个文件
// dir为文件目录名,name为文件名。这两个参数是必须有的,但并不一定要在自己的accept实现中使用
public boolean accept(File dir, String name)
{
// arr数组的第一个参数是扩展名
if (name.toLowerCase().endsWith(ext))
{
if (arr.length == 1) // arr数组只有一个参数(扩展名),直接返回true
{
return true;
}
Set<String> words = new HashSet<String>(new TextFile(new File(dir, name).getAbsolutePath(), "\\W+"));
for (int i = 1; i < arr.length; i++)
{
if (words.contains(arr[i]))
{
return true;
}
}
}
return false;
}
});
}
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
for (String dirItem : list)
{
System.out.println(dirItem);
}
}
}
练习2
package exercise.io;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.regex.Pattern;
import static net.mindview.util.Print.*;
public class E02_SortedDirList{
public static void main(String[] args)
{
SortedDirList s = new SortedDirList(new File("src/net/mindview/util"));
print(Arrays.asList(s.list()));
print(Arrays.asList(s.list("C.*"))); // 已C开头的
}
}
class SortedDirList
{
File path;
public SortedDirList()
{
this.path = new File("src/net/mindview/util");
}
public SortedDirList(File path)
{
this.path = path;
}
// 第一个list,产生整个列表
public String[] list()
{
String[] list = path.list();
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
return list;
}
// 第二个list,产生与参数(正则表达式)相匹配的列表
public String[] list(final String regex)
{
String[] list = path.list(new FilenameFilter()
{
private Pattern pattern = Pattern.compile(regex);
public boolean accept(File dir, String name)
{
return pattern.matcher(name).matches();
}
});
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
return list;
}
}
// : io/E03_DirSize.java
package exercise.io;
import static net.mindview.util.Print.print;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.regex.Pattern;
public class E03_DirSize
{
public static void main(String[] args)
{
DirSir("src/net/mindview/util", ".*");
}
// 只能计算dir路径下只有文件的情况,(不能计算子文件夹)
public static void DirSir(String dir, final String regex)
{
File path = new File(dir);
String[] list;
if(null == regex || "" == regex){
list = path.list();
}
else{
list = path.list(new FilenameFilter()
{
private Pattern pattern = Pattern.compile(regex);
public boolean accept(File dir, String name)
{
return pattern.matcher(name).matches();
}
});
}
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
print(Arrays.asList(list));
long total = 0;
long fs;
for (String dirItem : list)
{
fs = new File(path, dirItem).length(); // 文件字节数
print(dirItem + ", " + fs + " byte(s)");
total += fs;
}
print("=======================");
print(list.length + " file(s), " + total + " bytes");
}
}
练习4
// : io/E04_DirSize2.java
package exercise.io;
import java.io.*;
import net.mindview.util.*;
public class E04_DirSize2
{
public static void main(String[] args)
{
Directory.TreeInfo ti;
if (args.length == 0)
ti = Directory.walk("src/net/mindview/util");
else
ti = Directory.walk("../object", args[0]);
long total = 0;
for (File file : ti)
total += file.length();
System.out.println(ti.files.size() + " file(s), " + total + " bytes");
}
}
练习5
package exercise.io;
import java.io.File;
import java.io.IOException;
import net.mindview.util.Directory;
public class E05_ProcessFiles
{
public interface Strategy
{
void process(File file);
}
private Strategy strategy;
private String regex;
public E05_ProcessFiles(Strategy strategy, String regex)
{
this.strategy = strategy;
this.regex = regex;
}
public void start(String[] args)
{
try
{
if (args.length == 0)
processDirectoryTree(new File("src/net/mindview/util"));
else
for (String arg : args)
{
File fileArg = new File(arg);
if (fileArg.isDirectory())
{
processDirectoryTree(fileArg);
}
else if (arg.matches(regex))
{
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(), regex))
{
strategy.process(file.getCanonicalFile());
}
}
// Demonstration of how to use it:
public static void main(String[] args)
{
new E05_ProcessFiles(new E05_ProcessFiles.Strategy()
{
public void process(File file)
{
System.out.println(file);
}
}, "T.*e\\.java").start(args);
}
}
练习6
//: io/E06_ProcessFiles3.java
// {Args: . 1/1/06}
/****************** Exercise 6 *****************
* Use ProcessFiles to find all the Java
* source-code files in a particular directory
* subtree that have been modified after a
* particular date.
***********************************************/
package exercise.io;
import java.io.*;
import java.text.*;
import java.util.*;
import net.mindview.util.*;
public class E06_ProcessFiles3 {
public static void main(String[] args) {
String[] arr = { "src/net/mindview/util", "12/11/2017" };
search(arr);
}
// arr数组包含2个参数,第一个为文件路径,第二个为日期
public static void search(String[] arr) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
if (arr.length != 2) {
System.err.println("Usage: java E06_ProcessFiles3 path date");
return;
}
long tmp = 0;
try {
df.setLenient(false);
tmp = df.parse(arr[1]).getTime();
} catch (ParseException pe) {
pe.printStackTrace();
return;
}
final long modTime = tmp;
new ProcessFiles(new ProcessFiles.Strategy() {
public void process(File file) {
if (modTime < file.lastModified())
System.out.println(file);
}
}, "java").start(new String[] { arr[0] });
}
}
联系7
package exercise.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.ListIterator;
public class E07_ReadFile
{
public static void main(String[] args) throws IOException
{
readFile("D:/src/io/BufferedInputFile.java");
}
public static void readFile(String filename) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(filename));
LinkedList<String> ll = new LinkedList<String>();
String s = "";
while((s = br.readLine())!=null){
ll.add(s);
}
br.close();
for(ListIterator<String> it = ll.listIterator(ll.size()); it.hasPrevious();)
System.out.println(it.previous());
}
}
练习10
package exercise.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.ListIterator;
public class E10_ReadFile
{
public static void main(String[] args) throws IOException
{
String filename = "D:/ThinkInJava4/src/io/BufferedInputFile.java";
String[] wordsArr = {"String", "Reader"};
readFile(filename, wordsArr);
}
public static void readFile(String filename, String[] wordsArr) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(filename));
LinkedList<String> ll = new LinkedList<String>();
String s = "";
while ((s = br.readLine()) != null)
{
for (String word : wordsArr)
{
if (s.contains(word))
{
ll.add(s);
}
}
}
br.close();
// 逆序打印
for (ListIterator<String> it = ll.listIterator(ll.size()); it.hasPrevious();)
System.out.println(it.previous());
}
}
练习11
// : io/E11_GreenhouseControls2.java
// {Args: 5000000}
/******************
* Exercise 11 *************************** (Intermediate) In the innerclasses/GreenhouseController.java example,
* GreenhouseController contains a hard-coded set of events. Change the program so that it reads the events and their
* relative times from a text file. (Challenging: Use a Factory Method design pattern to build the events—see Thinking
* in Patterns (with Java) at www.MindView.net.)
*********************************************************/
package exercise.io;
import java.util.*;
import java.io.*;
import java.lang.reflect.*;
import innerclasses.GreenhouseControls;
import innerclasses.controller.*;
class GreenhouseControls2 extends GreenhouseControls
{
class Restart extends Event
{
private Event[] eventList;
public Restart(long delayTime)
{
super(delayTime);
}
public void action()
{
for (Event e : eventList)
{
e.start(); // Rerun each event
addEvent(e);
}
start();
addEvent(this); // Rerun this Event
}
public String toString()
{
return "Restarting system";
}
public void setEventList(Event[] eventList)
{
this.eventList = eventList;
}
}
class GHEventFactory
{
LinkedList<EventCreator> events = new LinkedList<EventCreator>();
class EventCreator
{
Constructor<Event> ctor;
long offset;
public EventCreator(Constructor<Event> ctor, long offset)
{
this.ctor = ctor;
this.offset = offset;
}
}
@SuppressWarnings("unchecked")
public GHEventFactory(String eventFile)
{
try
{
BufferedReader in = new BufferedReader(new FileReader(eventFile));
String s;
while ((s = in.readLine()) != null)
{
int colon = s.indexOf(':');
// Must use '$' instead of '.' to describe inner classes:
String className = s.substring(0, colon).trim();
Class<?> outer = className.equals("Restart") ? GreenhouseControls2.class : GreenhouseControls.class;
String type = outer.getSimpleName() + "$" + className;
long offset = Long.parseLong(s.substring(colon + 1).trim());
// Use Reflection to find and call the right constructor:
Class<Event> eventClass = (Class<Event>) Class.forName(type);
// Inner class constructors implicitly take the outer-class object as a first argument:
Constructor<Event> ctor = eventClass.getConstructor(new Class<?>[]
{
outer, long.class
});
events.add(new EventCreator(ctor, offset));
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
Iterator<Event> iterator()
{
return new Iterator<Event>()
{
Iterator<EventCreator> it = events.iterator();
public boolean hasNext()
{
return it.hasNext();
}
public Event next()
{
EventCreator ec = it.next();
Event returnVal = null;
try
{
returnVal = ec.ctor.newInstance(new Object[]
{
GreenhouseControls2.this, ec.offset
});
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return returnVal;
}
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
}
GHEventFactory gheFactory;
public GreenhouseControls2(String initFile)
{
gheFactory = new GHEventFactory(initFile);
// Now we need some logic to setup the system.
// The restart event requires a special attention.
LinkedList<Event> restartableEvents = new LinkedList<Event>();
Iterator<Event> it = gheFactory.iterator();
while (it.hasNext())
{
Event e = it.next();
if (e instanceof Bell || e instanceof Restart)
continue;
restartableEvents.add(e);
}
it = gheFactory.iterator();
while (it.hasNext())
{
Event e = it.next();
addEvent(e);
if (e instanceof Restart)
((Restart) e).setEventList(restartableEvents.toArray(new Event[0]));
}
}
}
public class E11_GreenhouseControls2
{
public static void main(String[] args)
{
GreenhouseControls2 gc = new GreenhouseControls2("GreenhouseConfig.dat");
try
{
if (args.length == 1)
gc.addEvent(new GreenhouseControls.Terminate(Long.parseLong(args[0])));
}
catch (NumberFormatException e)
{
System.err.println("Terminate event is not added!");
e.printStackTrace();
}
gc.run();
}
} /* Output: (Sample)
Thermostat on night setting
Light is on
Light is off
Greenhouse water is on
Greenhouse water is off
Bing!
Thermostat on day setting
Restarting system
Bing!
Thermostat on night setting
Light is on
Light is off
Greenhouse water is on
Greenhouse water is off
Bing!
Thermostat on day setting
Restarting system
Bing!
Thermostat on night setting
Light is on
Light is off
Greenhouse water is on
Greenhouse water is off
Terminating
*///:~
练习12
package exercise.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.ListIterator;
public class E12_ReadFile
{
public static void main(String[] args) throws IOException
{
String infilename = "D:/ThinkInJava4/src/io/BufferedInputFile.java";
String outfilename = "D:/ABufferedInputFile.java";
writeFile(readFile(infilename), outfilename);
}
public static LinkedList<String> readFile(String filename) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(filename));
LinkedList<String> ll = new LinkedList<String>();
String s = "";
while ((s = br.readLine()) != null)
{
ll.add(s);
}
br.close();
return ll;
}
public static void writeFile(LinkedList<String> ll, String filename) throws IOException
{
PrintWriter pw = new PrintWriter(filename);
int lineCount = ll.size();
for (ListIterator<String> it = ll.listIterator(ll.size()); it.hasPrevious();)
pw.write(lineCount-- + ":" + it.previous() + "\n");
pw.close();
}
}
练习14
// : io/E14_BufferPerformance.java
package exercise.io;
import java.io.*;
import java.util.*;
public class E14_BufferPerformance
{
static String file = "E14_BufferPerformance.out";
public static void main(String[] args) throws IOException
{
List<String> list = E12_ReadFile.readFile("E14_BufferPerformance.java");
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
int lineCount = 1;
long t1 = System.currentTimeMillis();
for (String s : list)
{
for (int i = 0; i < 10000; i++)
out.println(lineCount + ": " + s);
lineCount++;
}
long t2 = System.currentTimeMillis();
System.out.println("buffered: " + (t2 - t1));
out.close();
out = new PrintWriter(new FileWriter(file));
lineCount = 1;
t1 = System.currentTimeMillis();
for (String s : list)
{
for (int i = 0; i < 10000; i++)
out.println(lineCount + ": " + s);
lineCount++;
}
t2 = System.currentTimeMillis();
System.out.println("unbuffered: " + (t2 - t1));
out.close();
}
} /* Output: (Sample)
buffered: 3385
unbuffered: 4196
*///:~
练习17
// : io/E17_CharactersInfo.java
package exercise.io;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.mindview.util.TextFile;
public class E17_CharactersInfo
{
public static void main(String[] args)
{
Map<Character, Integer> charsStat = new HashMap<Character, Integer>();
for (String word : new TextFile("src/exercise/io/E17_CharactersInfo.java", "\\W+"))
{
for (int i = 0; i < word.length(); i++)
{
Character ch = word.charAt(i);
Integer freq = charsStat.get(ch);
charsStat.put(ch, freq == null ? 1 : freq + 1);
}
}
List<Character> keys = Arrays.asList(charsStat.keySet().toArray(new Character[0]));
Collections.sort(keys);
for (Character key : keys)
System.out.println(key + " => " + charsStat.get(key));
}
}
练习18
// Mine
package exercise.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;
public class E18_TextFile2 extends ArrayList<String>
{
private static final long serialVersionUID = -7862048067122202787L;
// 从文件中读一行
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();
}
// 将text数据写入文件
public static void write(String fileName, String text) throws FileNotFoundException
{
PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile());
try
{
out.print(text);
}
finally
{
out.close();
}
}
// 读一个文件,并已splitter分割
public E18_TextFile2(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);
}
// 按行读
public E18_TextFile2(String fileName) throws IOException
{
this(fileName, "\n");
}
public void write(String fileName)
{
try
{
PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile());
try
{
for (String item : this)
out.println(item);
}
finally
{
out.close();
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws IOException
{
String file = read("src/net/mindview/util/TextFile.java");
write("test.txt", file);
E18_TextFile2 text = new E18_TextFile2("test.txt");
text.write("test2.txt");
TreeSet<String> words = new TreeSet<String>(new E18_TextFile2("src/net/mindview/util/TextFile.java", "\\W+"));
System.out.println(words.headSet("a"));
}
}
练习19
// Mine
package exercise.io;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.mindview.util.BinaryFile;
public class E19_BytesInfo
{
public static void main(String[] args) throws IOException
{
String filename = "src/net/mindview/util/TextFile.java";
Map<Byte, Integer> map = func(filename);
List<Byte> list = new ArrayList<Byte>(map.keySet());
Collections.sort(list);
for(byte b : list){
System.out.println(b + " => " +map.get(b));
}
}
public static Map<Byte, Integer> func(String filename) throws IOException
{
Map<Byte, Integer> map = new HashMap<Byte, Integer>();
byte[] byteArr = BinaryFile.read(filename);
for (byte b : byteArr)
{
Integer num = map.get(b);
map.put(b, num == null ? 1 : num + 1);
}
return map;
}
}
练习20
package exercise.io;
import java.io.File;
import java.io.IOException;
import java.util.List;
import net.mindview.util.BinaryFile;
import net.mindview.util.Directory;
public class E20_ClassSignatureChecker
{
public static void main(String[] args) throws IOException
{
String filename = "D:/ThinkInJava4";
String ext = ".*class";
func(filename,ext);
}
public static void func(String filename, String reg) throws IOException
{
final byte[] signature =
{
(byte) 202, (byte) 254, (byte) 186, (byte) 190
}; // CAFEBABE
List<File> fileList = Directory.walk(filename, reg).files;
for (File file : fileList)
{
byte[] byteArr = BinaryFile.read(file);
for (int i = 0; i < 4; i++)
{
if (byteArr[i] != signature[i])
{
System.out.println(file.getPath() + "/" + file.getName() + " is corrupt");
break;
}
}
}
System.out.println("done");
}
}
相关文章
- 暂无相关文章
用户点评