【问题标题】:How to get file content in java?如何在java中获取文件内容?
【发布时间】:2011-08-04 05:00:18
【问题描述】:

为了获取 txt 文件的内容,我通常使用扫描仪并遍历每一行以获取内容:

Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
    String str = sc.nextLine();                     
}

java api 是否提供了一种通过一行代码获取内容的方法,例如:

String content = FileUtils.readFileToString(new File("file.txt"))

【问题讨论】:

    标签: java java-io


    【解决方案1】:

    经过一番测试,我发现BufferedReaderScanner 在各种情况下都有问题(前者经常检测不到新行,而后者经常去除空格,例如,从 org.json 库)。还有其他可用的方法,但问题是它们仅在某些 Java 版本之后才受支持(例如,这对 Android 开发人员不利),并且您可能不想仅出于这样的单一目的使用 Guava 或 Apache 公共库。因此,我的解决方案是将整个文件读取为字节并将其转换为字符串。下面的代码取自我的一个爱好项目:

        /**
         * Get byte array from an InputStream most efficiently.
         * Taken from sun.misc.IOUtils
         * @param is InputStream
         * @param length Length of the buffer, -1 to read the whole stream
         * @param readAll Whether to read the whole stream
         * @return Desired byte array
         * @throws IOException If maximum capacity exceeded.
         */
        public static byte[] readFully(InputStream is, int length, boolean readAll)
                throws IOException {
            byte[] output = {};
            if (length == -1) length = Integer.MAX_VALUE;
            int pos = 0;
            while (pos < length) {
                int bytesToRead;
                if (pos >= output.length) {
                    bytesToRead = Math.min(length - pos, output.length + 1024);
                    if (output.length < pos + bytesToRead) {
                        output = Arrays.copyOf(output, pos + bytesToRead);
                    }
                } else {
                    bytesToRead = output.length - pos;
                }
                int cc = is.read(output, pos, bytesToRead);
                if (cc < 0) {
                    if (readAll && length != Integer.MAX_VALUE) {
                        throw new EOFException("Detect premature EOF");
                    } else {
                        if (output.length != pos) {
                            output = Arrays.copyOf(output, pos);
                        }
                        break;
                    }
                }
                pos += cc;
            }
            return output;
        }
    
        /**
         * Read the full content of a file.
         * @param file The file to be read
         * @param emptyValue Empty value if no content has found
         * @return File content as string
         */
        @NonNull
        public static String getFileContent(@NonNull File file, @NonNull String emptyValue) {
            if (file.isDirectory()) return emptyValue;
            try {
                return new String(readFully(new FileInputStream(file), -1, true), Charset.defaultCharset());
            } catch (IOException e) {
                e.printStackTrace();
                return emptyValue;
            }
        }
    

    您可以简单地使用getFileContent(file, "") 来读取文件的内容。

    【讨论】:

      【解决方案2】:

      您可以将 FileReader 类与 BufferedReader 一起使用来读取文本文件。

      File fileToRead = new File("file.txt");
      
      try( FileReader fileStream = new FileReader( fileToRead ); 
          BufferedReader bufferedReader = new BufferedReader( fileStream ) ) {
      
          String line = null;
      
          while( (line = bufferedReader.readLine()) != null ) {
              //do something with line
          }
      
          } catch ( FileNotFoundException ex ) {
              //exception Handling
          } catch ( IOException ex ) {
              //exception Handling
      }
      

      【讨论】:

        【解决方案3】:

        不是内置 API - 但Guava 确实如此,除此之外还有其他宝藏。 (这是一个很棒的图书馆。)

        String content = Files.toString(new File("file.txt"), Charsets.UTF_8);
        

        有类似的方法可以读取任何Readable,或将二进制文件的全部内容加载为字节数组,或将文件读入字符串列表等。

        请注意,此方法现已弃用。新的等价物是:

        String content = Files.asCharSource(new File("file.txt"), Charsets.UTF_8).read();
        

        【讨论】:

        • Files#toString 已弃用。文档状态:Prefer {@code asCharSource(file, charset).read()}. This method is scheduled to be removed in January 2019.
        【解决方案4】:
        import java.io.IOException;
        import java.nio.file.Files;
        import java.nio.file.Paths;
        
        public static void main(String[] args) throws IOException {
            String content = Files.readString(Paths.get("foo"));
        }
        

        来自https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)

        【讨论】:

        【解决方案5】:

        对于 Java 7,有一个类似的 API。

        Files.readAllLines(Path path, Charset cs)

        【讨论】:

        • 链接好像失效了。
        • 已更新固定链接。
        • 酷,您也可以使用 readAllBytes() 并在没有任何第三方库的情况下执行以下一行: String content = new String (Files.readAllBytes(new File("/my/file.txt" )).toPath()))
        【解决方案6】:

        commons-io 有:

        IOUtils.toString(new FileReader("file.txt"), "utf-8");
        

        【讨论】:

          猜你喜欢
          • 2014-06-13
          • 1970-01-01
          • 2014-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多