将整个文本文件转换为 Java 中的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3849692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 05:49:07  来源:igfitidea点击:

Whole text file to a String in Java

javafilefile-io

提问by Betamoo

Does Java has a one line instruction to read to a text file, like what C# has?

Java 是否有一行指令来读取文本文件,就像 C# 一样?

I mean, is there something equivalent to this in Java?:

我的意思是,在 Java 中是否有与此等效的东西?:

String data = System.IO.File.ReadAllText("path to file");

If not... what is the 'optimal way' to do this...?

如果不是......这样做的“最佳方式”是什么......?

Edit:
I prefer a way within Java standard libraries... I can not use 3rd party libraries..

编辑:
我更喜欢 Java 标准库中的一种方式......我不能使用 3rd 方库..

采纳答案by Neeme Praks

Java 11 adds support for this use-case with Files.readString, sample code:

Java 11 使用Files.readString添加了对此用例的支持,示例代码:

Files.readString(Path.of("/your/directory/path/file.txt"));

Before Java 11, typical approach with standard libraries would be something like this:

在 Java 11 之前,标准库的典型方法是这样的:

public static String readStream(InputStream is) {
    StringBuilder sb = new StringBuilder(512);
    try {
        Reader r = new InputStreamReader(is, "UTF-8");
        int c = 0;
        while ((c = r.read()) != -1) {
            sb.append((char) c);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return sb.toString();
}

Notes:

笔记:

  • in order to read text from file, use FileInputStream
  • if performance is importantand you are reading large files, it would be advisable to wrap the stream in BufferedInputStream
  • the stream should be closed by the caller
  • 为了从文件中读取文本,请使用 FileInputStream
  • 如果性能很重要并且您正在读取大文件,则建议将流包装在 BufferedInputStream 中
  • 流应该由调用者关闭

回答by Jon Skeet

Not within the main Java libraries, but you can use Guava:

不在主要的 Java 库中,但您可以使用Guava

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

Or to read lines:

或阅读行:

List<String> lines = Files.readLines( new File("path.txt"), Charsets.UTF_8 );

Of course I'm sure there are other 3rd party libraries which would make it similarly easy - I'm just most familiar with Guava.

当然,我确信还有其他 3rd 方库可以使这同样简单——我只是最熟悉 Guava。

回答by Bozho

apache commons-iohas:

apache commons-io有:

String str = FileUtils.readFileToString(file, "utf-8");

But there is no such utility in the standard java classes. If you (for some reason) don't want external libraries, you'd have to reimplement it. Hereare some examples, and alternatively, you can see how it is implemented by commons-io or Guava.

但是在标准的 java 类中没有这样的实用程序。如果您(出于某种原因)不想要外部库,则必须重新实现它。这里有一些例子,或者,你可以看到它是如何通过 commons-io 或 Guava 实现的。

回答by dimo414

Java 7 improves on this sorry state of affairs with the Filesclass (not to be confused with Guava's class of the same name), you can get all lines from a file - without external libraries - with:

Java 7 改进了类的这种令人遗憾的状态Files(不要与 Guava 的同名类混淆),您可以从文件中获取所有行 - 无需外部库 - 使用:

List<String> fileLines = Files.readAllLines(path, StandardCharsets.UTF_8);

Or into one String:

或成一个字符串:

String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
// or equivalently:
StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(path)));

If you need something out of the box with a clean JDK this works great. That said, why are you writing Java without Guava?

如果您需要使用干净的 JDK 开箱即用的东西,这非常有用。也就是说,为什么要在没有 Guava 的情况下编写 Java?

回答by SzB

No external libraries needed. The content of the file will be buffered before converting to string.

不需要外部库。在转换为字符串之前,文件的内容将被缓冲。

Path path = FileSystems.getDefault().getPath(directory, filename);
String fileContent = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);

回答by SzB

No external libraries needed. The content of the file will be buffered before converting to string.

不需要外部库。在转换为字符串之前,文件的内容将被缓冲。

  String fileContent="";
  try {
          File f = new File("path2file");
          byte[] bf = new byte[(int)f.length()];
          new FileInputStream(f).read(bf);
          fileContent = new String(bf, "UTF-8");
      } catch (FileNotFoundException e) {
          // handle file not found exception
      } catch (IOException e) {
          // handle IO-exception
      }

回答by Kris

In Java 8(no external libraries) you could use streams. This code reads a file and puts all lines separated by ', ' into a String.

Java 8(没有外部库)中,您可以使用流。此代码读取一个文件并将所有由 ', ' 分隔的行放入一个字符串中。

try (Stream<String> lines = Files.lines(myPath)) {
    list = lines.collect(Collectors.joining(", "));
} catch (IOException e) {
    LOGGER.error("Failed to load file.", e);
}

回答by gomisha

Here are 3 ways to read a text file in one line, without requiring a loop. I documented 15 ways to read from a file in Javaand these are from that article.

以下是在一行中读取文本文件的 3 种方法,无需循环。我记录了15 种在 Java 中读取文件的方法,这些方法来自那篇文章。

Note that you still have to loop through the list that's returned, even though the actual call to read the contents of the file requires just 1 line, without looping.

请注意,您仍然必须遍历返回的列表,即使读取文件内容的实际调用只需要 1 行,而无需循环。

1) java.nio.file.Files.readAllLines() - Default Encoding

1) java.nio.file.Files.readAllLines() - 默认编码

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

public class ReadFile_Files_ReadAllLines {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\temp\sample-10KB.txt";
    File file = new File(fileName);

    List  fileLinesList = Files.readAllLines(file.toPath());

    for(String line : fileLinesList) {
      System.out.println(line);
    }
  }
}

2) java.nio.file.Files.readAllLines() - Explicit Encoding

2) java.nio.file.Files.readAllLines() - 显式编码

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

public class ReadFile_Files_ReadAllLines_Encoding {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\temp\sample-10KB.txt";
    File file = new File(fileName);

    //use UTF-8 encoding
    List  fileLinesList = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);

    for(String line : fileLinesList) {
      System.out.println(line);
    }
  }
}

3) java.nio.file.Files.readAllBytes()

3) java.nio.file.Files.readAllBytes()

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class ReadFile_Files_ReadAllBytes {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\temp\sample-10KB.txt";
    File file = new File(fileName);

    byte [] fileBytes = Files.readAllBytes(file.toPath());
    char singleChar;
    for(byte b : fileBytes) {
      singleChar = (char) b;
      System.out.print(singleChar);
    }
  }
}

回答by Naman

With JDK/11, you can read a complete file at a Pathas a string using Files.readString(Path path):

使用 JDK/11,您可以使用以下命令读取 a 处的完整文件Path作为字符串Files.readString(Path path)

try {
    String fileContent = Files.readString(Path.of("/foo/bar/gus"));
} catch (IOException e) {
    // handle exception in i/o
}

the method documentation from the JDK reads as follows:

JDK 中的方法文档如下:

/**
 * Reads all content from a file into a string, decoding from bytes to characters
 * using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.
 * The method ensures that the file is closed when all content have been read
 * or an I/O error, or other runtime exception, is thrown.
 *
 * <p> This method is equivalent to:
 * {@code readString(path, StandardCharsets.UTF_8) }
 *
 * @param   path the path to the file
 *
 * @return  a String containing the content read from the file
 *
 * @throws  IOException
 *          if an I/O error occurs reading from the file or a malformed or
 *          unmappable byte sequence is read
 * @throws  OutOfMemoryError
 *          if the file is extremely large, for example larger than {@code 2GB}
 * @throws  SecurityException
 *          In the case of the default provider, and a security manager is
 *          installed, the {@link SecurityManager#checkRead(String) checkRead}
 *          method is invoked to check read access to the file.
 *
 * @since 11
 */
public static String readString(Path path) throws IOException 

回答by mir

Not quite a one liner and probably obsolete if using JDK 11 as posted by nullpointer. Still usefull if you have a non file input stream

如果使用 nullpointer 发布的 JDK 11,则不完全是一个班轮,并且可能已经过时。如果您有非文件输入流,仍然很有用

InputStream inStream = context.getAssets().open(filename);
Scanner s = new Scanner(inStream).useDelimiter("\A");
String string = s.hasNext() ? s.next() : "";
inStream.close();
return string;