`
liugang594
  • 浏览: 987497 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

【转】Stupid Scanner tricks...

 
阅读更多
Posted by pat on October 24, 2004 at 1:18 AM PDT

One of the things I've always wanted in Java is a "one liner" trick to read all of the text from a stream. For example, I often want to be able to grab the contents of a URL or file as a simple String, without a lot of typing. The URL class tantalizingly holds out its getContent() method, but sadly, content handlers were never really taken seriously. I don't even particularly care about performance, I'd just like something for the simple case, in standard Java, that's not too hard to remember. Well, the Java 1.5 java.util.Scanner class finally has the answer...

 

Suppose I have a stream:

    InputStream source = new URL("http://pat.net/misc/foo.txt").openStream();

The canonical way to gather it to a String has always been to use a BufferedReader, e.g.

    BufferedReader br = new BufferedReader( new InputStreamReader( source ) );
    StringBuffer text = new StringBuffer();
    for ( String line; (line = br.readLine()) ! = null )
        text.append( line );

This is about 4 lines of tediousness code (assuming the resulting StringBuffer is good enough), uses two classes, a loop, and too many parentheses. I must have typed code like this a million times, as I bet a lot of people have.

I've often been tempted to try to shorten it a bit using the DataInputStream readFully() method:

    byte [] buf = new byte[ source.available() ];
    new DataInputStream( source ).readFully( buf );
    String text = new String( buf );

That would be a bit less typing and involve only an array and a class. The problem is that it relies on the input stream's available() method to reflect the total size of the data to be returned... which in general it doesn't. The available() method works for files and you could always substitute your own size if you can get it from other meta-data, but it's still a messy solution and doesn't exactly roll off of the finger tips.

Finally now with Java 1.5's Scanner I have a true one-liner:

    String text = new Scanner( source ).useDelimiter("\\A").next();

One line, one class. The only tricky is to remember the regex \A, which matches the beginning of input. This effectively tells Scanner to tokenize the entire stream, from beginning to (illogical) next beginning. As a bonus, Scanner can work not only with an InputStream as the source, but also a File, Channel, or anything that implements the new java.lang.Readable interface. For example, to read a file:

    String text = new Scanner( new File("poem.txt") ).useDelimiter("\\A").next();

Finally, before someone chastizes me I should point out that you can accommodate a specific character set with all of the above examples. In the first you'd set the charset in the InputStreamReader, in the second you'd specify it with the String constructor, and in the Scanner example you can pass a charset to the constructor.

Enjoy!

分享到:
评论

相关推荐

    8.javaScanner类.zip

    8.javaScanner类.zip8.javaScanner类.zip8.javaScanner类.zip8.javaScanner类.zip8.javaScanner类.zip8.javaScanner类.zip8.javaScanner类.zip8.javaScanner类.zip8.javaScanner类.zip8.javaScanner类.zip8.java...

    sonar-scanner-4.0.0.1744-windows.rar

    sonar-scanner-4.0.0.1744-windowssonar-scanner-4.0.0.1744-windowssonar-scanner-4.0.0.1744-windowssonar-scanner-4.0.0.1744-windows

    36.java数据输入Scanner.zip

    36.java数据输入Scanner.zip36.java数据输入Scanner.zip36.java数据输入Scanner.zip36.java数据输入Scanner.zip36.java数据输入Scanner.zip36.java数据输入Scanner.zip36.java数据输入Scanner.zip36.java数据输入...

    AdvancedIPScanner253850.zip

    Network Scanner(局域网IP扫描工具)是一个免费的多线程的IP,NetBIOS和SNMP的扫描仪。其目的是为系统管理员和对计算机安全感兴趣的用户。检测用户自定义的端口并报告已打开的端口,解析主机域名和自动检测您的本地IP...

    Windows.Devices.Scanners.dll

    Windows.Devices.Scanners.dll

    在Java中,Scanner类.zip

    String[] tokens = scanner.useDelimiter(",").next().split(","); ``` 此外,`Scanner`类提供了hasNext()系列方法,用于检查是否还有更多的输入。这在循环读取输入时非常有用,可以防止程序因尝试读取不存在的数据...

    sonar-scanner-cli-3.0.3.778-windows.zip

    3. `conf` 目录:可能包含默认配置文件,如`sonar-scanner.properties`,你可以根据项目需求进行修改。 4. 可能还有其他文档、许可证文件等。 使用SonarScanner的基本步骤如下: 1. **配置**:在项目根目录下创建...

    web vulnerability scanner 10.x

    web vulnerability scanner 10.x经典的网站漏洞测试工具

    Advanced IP Scanner.exe

    可以方便的监控活动IP地址,对网段IP地址进行全面扫描

    JAVA Scanner输入.pdf

    JAVA Scanner输入.pdf

    Acunetix Web Vulnerability Scanner8.x Enterprise Edition KeyGen

    Acunetix Web Vulnerability Scanner8.x Enterprise Edition KeyGen 使用说明:先通过官方地址下载最新的企业版安装包[注册机只支持企业版,不支持free版],安装完成后关闭程序打开破解补丁,点Patch后可正常注册了,...

    BarcodeScanner4.2.apk

    BarcodeScanner4.2.apk )

    sonar-scanner-cli-4.0.0.1744-linux.zip

    创建或编辑`~/.sonar/scanner.properties`文件,添加以下内容: ``` sonar.projectKey=<你的项目标识> sonar.sources=<你的源代码路径> sonar.host.url=<你的SonarQube服务器URL> sonar.login=<你的SonarQube...

    Java中Scanner用法.doc

    scanner.useDelimiter(System.getProperty("line.separator")); while (scanner.hasNext()) { parseLine(scanner.next()); } scanner.close(); } catch (FileNotFoundException e) { System.out.println(e); ...

    Java Scanner 类.pdf

    String line = scanner.nextLine(); System.out.println("输入的内容是:" + line); } ``` 这段代码会持续读取用户的输入,直到没有更多输入为止,每次读取一行(包含空格)。 5. 使用`nextLine()`方法: 当...

    tomcat-memshell-scanner.jsp

    Java内存马查杀 这里推荐几款内存马查杀工具 java-memshell-scanner:通过jsp脚本扫描并查杀各类... 只需要将tomcat-memshell-scanner.jsp放在可能被注入内存马的web录下,然后使用浏览器访问即可直接获得扫描结果。

    Acunetix_Web_Vulnerability_Scanner_10.rar

    Acunetix Web Vulnerability Scanner 10.x Consultant Edition KeyGen By Hmily[LCG] 神器应用扫描

Global site tag (gtag.js) - Google Analytics