Java扫描程序仅读取前2048个字节

Java扫描程序仅读取前2048个字节

本文介绍了Java扫描程序仅读取前2048个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用java.util.Scanner通过以下代码从类路径中读取文件内容:

I'm using java.util.Scanner to read file contents from classpath with this code:

String path1 = getClass().getResource("/myfile.html").getFile();

System.out.println(new File(path1).length()); // 22244 (correct)

String file1 = new Scanner(new File(path1)).useDelimiter("\\Z").next();
System.out.println(file1.length()); // 2048 (first 2k only)

代码从命令中运行(Maven测试)

Code runs from idea with command (maven test)

/Library/Java/JavaVirtualMachines/jdk1.7.0_25.jdk/Contents/Home/bin/java -Dmaven.home=/usr/share/java/maven-3.0.4 -Dclassworlds.conf=/usr/share/java/maven-3.0.4/bin/m2.conf -Didea.launcher.port=7533 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA 12 CE.app/bin" -Dfile.encoding=UTF-8 -classpath "/usr/share/java/maven-3.0.4/boot/plexus-classworlds-2.4.jar:/Applications/IntelliJ IDEA 12 CE.app/lib/idea_rt.jar" com.intellij.rt.execution.application.AppMain org.codehaus.classworlds.Launcher --fail-fast --strict-checksums test

它在我的win7机器上运行完美.但是在我移至Mac之后,相同的测试失败了.我试图用Google搜索,但没有找到太多=(

It was running perfectly on my win7 machine. But after I moved to mac same tests fail.I tried to google but didn't find much =(

为什么带定界符\ Z的扫描仪在win7上将我的整个文件读入字符串,但在Mac上却不这样做?我知道还有更多读取文件的方法,但是我喜欢这种单行代码,并且想了解为什么它不起作用.谢谢.

Why Scanner with delimiter \Z read my whole file into a string on win7 but won't do it on mac?I know there're more ways to read a file, but I like this one-liner and want to understand why it's not working.Thanks.

推荐答案

以下是Java的一些相关信息

Here is some info from java about it

http://docs.oracle .com/javase/7/docs/api/java/util/regex/Pattern.html

\ z输入的结尾

行终止符

换行符('\ n'),换行符紧随其后的是换行符("\ r \ n"),即独立的回车符('\ r'),下一行字符('\ u0085'),A行分隔符('\ u2028')或段落分隔符字符('\ u2029).

A newline (line feed) character ('\n'), A carriage-return characterfollowed immediately by a newline character ("\r\n"), A standalonecarriage-return character ('\r'), A next-line character ('\u0085'), Aline-separator character ('\u2028'), or A paragraph-separatorcharacter ('\u2029).

因此,请使用\z代替\Z

这篇关于Java扫描程序仅读取前2048个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 18:38