java scanner 用不了_java Scanner具有神奇的作用可惜大部分java开发人员不知
3. Scanner
有無數 Java 工具能幫助您構建解析器,很多函數語言已成功構建解析器函數庫(解析器選擇器)。但如果要解析的是逗號分隔值文件,或空格分隔文本文件,又怎么辦呢?大多數工具用在此處就過于隆重了,而
String.split() 又不夠。(對于正則表達式,請記住一句老話:“ 您有一個問題,用正則表達式解決。那您就有兩個問題了。”)
Java 平臺的 Scanner 類會是這些類中您最好的選擇。以輕量級文本解析器為目標,Scanner 提供了一個相對簡單的 API,用于提取結構化文本,并放入強類型的部分。想象一下,如果您愿意,一組類似 DSL 的命令(
源自 Terry Pratchett Discworld 小說)排列在文本文件中,如清單 7:
清單 7. Igor 的任務
fetch 1 head
fetch 3 eye
fetch 1 foot
attach foot to head
attach eye to head
admire? 您,或者是本例中稱為 Igor的私仆,能輕松使用 Scanner 解析這組違法命令,如清單 8 所示:
清單 8. Igor 的任務,由 Scanner 解析
import java.io.*;
import java.util.*;
public class Igor?? implements IPersonalServant
{
public boolean can(String cmd)
{
if (cmd.equals("fetch body parts"))
return true;
if (cmd.equals("attach body parts"))
return true;
else
return false;
}
public void process(File commandFile)? throws FileNotFoundException
{
Scanner scanner = new Scanner(commandFile);? // Commands come in a verb/number/noun or verb form
while (scanner.hasNext())
{
String verb = scanner.next();
if (verb.equals("fetch"))
{
int num = scanner.nextInt();
String type = scanner.next();
fetch (num, type);
}
else if (verb.equals("attach"))
{
String item = scanner.next();
String to = scanner.next();
String target = scanner.next();
attach(item, target);
}
else if (verb.equals("admire"))
{
admire();
}
else
{
System.out.println("I don't know how to "+ verb + ", marthter.");
}
}
}
public void fetch(int number, String type)
{
if (parts.get(type) == null)
{
System.out.println("Fetching " + number + " " + type + (number > 1 ? "s" : "") + ", marthter!");
parts.put(type, number);
}
else
{
System.out.println("Fetching " + number + " more "? + type + (number > 1 ? "s" : "") + ", marthter!");
Integer currentTotal = parts.get(type);
parts.put(type, currentTotal + number);
}
System.out.println("We now have " + parts.toString());
}
public void attach(String item, String target)
{
System.out.println("Attaching the " + item + " to the " +? arget + ", marthter!");
}
public void admire()
{
System.out.println("It'th quite the creathion, marthter");
}
private Map parts = new HashMap();
}?? 假設 Igor 已在 ServantLoader 中注冊,可以很方便地將 can() 調用改得更實用,并重用前面的 Servant 代碼,如清單 9 所示:
清單 9. Igor 做了什么
import java.io.*;
import java.util.*;
public class Servant
{
public static void main(String[] args)throws IOException
{
ServiceLoader servantLoader = ServiceLoader.load(IPersonalServant.class);
IPersonalServant i = null;
for (IPersonalServant ii : servantLoader)
if (ii.can("fetch body parts"))
i = ii;
if (i == null)
throw new IllegalArgumentException("No suitable servant found");
for (String arg : args)
{
i.process(new File(arg));
}
}
}
真正 DSL 實現顯然不會僅僅打印到標準輸出流。我把追蹤哪些部分、跟隨哪些部分的細節留待給您(當然,還有忠誠的 Igor)。
總結
以上是生活随笔為你收集整理的java scanner 用不了_java Scanner具有神奇的作用可惜大部分java开发人员不知的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java画板抽象类_java 中的 抽象
- 下一篇: mysql awr flush_Orac