在 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

But this code is reading only first 1024 characters from input file(MyFile.txt).

我找不到原因。

使用 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);
}

你可以看看this问题。很好。

感谢您的回答:

终于找到解决办法了-

 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();

盗自 here...