Bet*_*moo 55 java file-io file
Java是否有一行读取文本文件,就像C#一样?
我的意思是,在Java中是否存在与此类似的东西?:
String data = System.IO.File.ReadAllText("path to file");
Run Code Online (Sandbox Code Playgroud)
如果不是......这样做的"最佳方式"是什么?
编辑:
我更喜欢Java标准库中的一种方式...我不能使用第三方库..
Boz*_*zho 45
String str = FileUtils.readFileToString(file, "utf-8");
Run Code Online (Sandbox Code Playgroud)
但是标准java类中没有这样的实用程序.如果您(由于某种原因)不想要外部库,则必须重新实现它.以下是一些示例,您也可以看到它是如何通过commons-io或Guava实现的.
Jon*_*eet 27
不在主Java库中,但您可以使用Guava:
String data = Files.asCharSource(new File("path.txt"), Charsets.UTF_8).read();
Run Code Online (Sandbox Code Playgroud)
或读取行:
List<String> lines = Files.readLines( new File("path.txt"), Charsets.UTF_8 );
Run Code Online (Sandbox Code Playgroud)
当然我肯定还有其他第三方库可以让它同样容易 - 我只是最熟悉番石榴.
dim*_*414 24
Java 7改进了这个令人遗憾的事务状态Files(不要与Guava的同名类混淆),你可以从文件中获取所有行 - 没有外部库 - 用:
List<String> fileLines = Files.readAllLines(path, StandardCharsets.UTF_8);
Run Code Online (Sandbox Code Playgroud)
或者成一个字符串:
String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
// or equivalently:
StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(path)));
Run Code Online (Sandbox Code Playgroud)
如果你需要一个干净的JDK开箱即用的东西,那么效果很好.那就是说,为什么你在没有番石榴的情况下编写Java?
Nee*_*aks 22
AFAIK,没有标准库的单行程.标准库的典型方法是这样的:
Files.readString(Path.of("/your/directory/path/file.txt"));
Run Code Online (Sandbox Code Playgroud)
笔记:
Kri*_*ris 10
在Java 8(没有外部库)中,您可以使用流.此代码读取文件并将所有以","分隔的行放入String中.
try (Stream<String> lines = Files.lines(myPath)) {
list = lines.collect(Collectors.joining(", "));
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
Run Code Online (Sandbox Code Playgroud)
使用 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
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48301 次 |
| 最近记录: |