繁体   English   中英

使用java中的扫描仪一次完成文件读取

[英]Complete file read at once using scanner in java

我必须用 Java 读取文本文件,为此我使用了以下代码:

Scanner scanner = new Scanner(new InputStreamReader(
    ClassLoader.getSystemResourceAsStream("mock_test_data/MyFile.txt")));

scanner.useDelimiter("\\Z");
String content = scanner.next();
scanner.close();

据我所知StringMAX_LENGTH 2^31-1

但是此代码仅从输入文件(MyFile.txt)中读取前 1024 个字符。

我无法找到原因。

感谢您的回答:

最后我找到了解决方案-

 String path = new File("src/mock_test_data/MyFile.txt").getAbsolutePath();
 File file = new File(path);
 FileInputStream fis = new FileInputStream(file);
 byte[] data = new byte[(int) file.length()];
 fis.read(data);
 fis.close();
 content = new String(data, "UTF-8");

因为我必须一次阅读一个很长的文件。

我已经阅读了一些评论,因此我认为有必要指出这个答案并不关心实践的好坏。 对于需要快速解决方案的懒惰人来说,这是一个愚蠢的好知道的扫描仪技巧。

final String res = "mock_test_data/MyFile.txt"; 

String content = new Scanner(ClassLoader.getSystemResourceAsStream(res))
     .useDelimiter("\\A").next();

这里...

使用BufferedReader示例,适用于大文件:

public String getFileStream(final String inputFile) {
        String result = "";
        Scanner s = null;

        try {
            s = new Scanner(new BufferedReader(new FileReader(inputFile)));
            while (s.hasNext()) {
                result = result + s.nextLine();
            }
        } catch (final IOException ex) {
            ex.printStackTrace();
        } finally {
            if (s != null) {
                s.close();
            }
        }
        return result;
}

FileInputStream用于较小的文件。

使用readAllBytes并对它们进行编码也可以解决问题。

static String readFile(String path, Charset encoding) 
  throws IOException 
{
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}

你可以看看这个问题。 这很棒。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM