日期:2014-05-20  浏览次数:20752 次

关于《think in java》里的String源码的运行问题,求大牛解释!!!
问题:我运行后,发现终端没有任何数据显示,但是think in java的结果如下:
0: strings: 4
1: simple: 10
2: the: 28
3: Ssct: 26
4: class: 7
...........
下面是我的源码(也是书上的源码):

//: strings/JGrep.java
// A very simple version of the "grep" program.
// {Args: JGrep.java "\\b[Ssct]\\w+"}
import java.util.regex.*;
import net.mindview.util.*;

public class JGrep {
  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 of file:
int index=0;
Matcher m=p.matcher("");
for(String line :new TextFile(args[0])){
//System.out.println(line);
m.reset(line);
while(m.find())
System.out.println(index++ +": "+m.group()+": "+m.start());
}

}

}

上面导入的import net.mindview.util.*;不属于java本身,而是作者自己写的,所以我直接兴建了一个类(直接复制作者源码下面的一个类-TextFile,这里只用到了这个类,不用导入整个包)
TextFile 具体内容如下:
//: net/mindview/util/TextFile.java
// Static functions for reading and writing text files as
// a single string, and treating a file as an ArrayList.

import java.io.*;
import java.util.*;

public class TextFile extends ArrayList<String> {
  // Read a file as a single string:
  public static String read(String fileName) {
  StringBuilder sb = new StringBuilder();
  try {
  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();
  }
  } catch(IOException e) {
  throw new RuntimeException(e);
  }
  return sb.toString();
  }
  // Write a single file in one method call:
  public static void write(String fileName, String text) {
  try {
  PrintWriter out = new PrintWriter(
  new File(fileName).getAbsoluteFile());
  try {
  out.print(text);
  } finally {
  out.close();
  }
  } catch(IOException e) {
  throw new RuntimeException(e);
  }
  }
  // Read a file, split by any regular expression:
  public TextFile(String fileName, String splitter) {
  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 TextFile(String fileName) {
  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);
  }
  }
  // Simple test:
  public static void main(String[] args) {
  String file = read("TextFile.java");
  write("test.txt", file);
  TextFile text = new TextFile("test.txt");
  text.write("test2.txt");