Java是否有一行读取文本文件,就像C#一样?
我的意思是,在Java中是否存在与此类似的东西?:
String data = System.IO.File.ReadAllText("path to file");
如果不是......这样做的“最佳方式”是什么......?
修改
我更喜欢Java标准库中的一种方式......我不能使用第三方库..
答案 0 :(得分:45)
String str = FileUtils.readFileToString(file, "utf-8");
但是标准java类中没有这样的实用程序。如果您(出于某种原因)不想要外部库,则必须重新实现它。 Here是一些示例,或者,您可以看到它是如何通过commons-io或Guava实现的。
答案 1 :(得分:27)
不在主Java库中,但您可以使用Guava:
String data = Files.asCharSource(new File("path.txt"), Charsets.UTF_8).read();
或读取行:
List<String> lines = Files.readLines( new File("path.txt"), Charsets.UTF_8 );
当然,我确信还有其他第三方库可以让它同样容易 - 我只是最熟悉番石榴。
答案 2 :(得分:23)
Java 7改进了Files
类的这种令人遗憾的事态(不要与Guava的class of the same name混淆),你可以从文件中获取所有行 - 没有外部库 - 用:< / p>
List<String> fileLines = Files.readAllLines(path, StandardCharsets.UTF_8);
或者换成一个字符串:
String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
// or equivalently:
StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(path)));
如果你需要一个干净的JDK开箱即用的东西,那么效果很好。那就是说,为什么你在没有番石榴的情况下编写Java?
答案 3 :(得分:22)
Java 11使用Files.readString添加了对此用例的支持,示例代码:
Files.readString(Path.of("/your/directory/path/file.txt"));
在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();
}
注意:
答案 4 :(得分: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);
}
答案 5 :(得分:4)
在JDK / 11中,您可以使用 Path
作为字符串读取Files.readString(Path path)
的完整文件:
try {
String fileContent = Files.readString(Path.of("/foo/bar/gus"));
} catch (IOException e) {
// handle exception in i/o
}
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
答案 6 :(得分:1)
不需要外部库。在转换为字符串之前,将缓冲文件的内容。
Path path = FileSystems.getDefault().getPath(directory, filename);
String fileContent = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
答案 7 :(得分:0)
不需要外部库。在转换为字符串之前,将缓冲文件的内容。
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
}
答案 8 :(得分:0)
以下是在一行中读取文本文件的3种方法,无需循环。我记录了15 ways to read from a file in Java,这些来自那篇文章。
请注意,您仍然必须遍历返回的列表,即使实际调用读取文件内容只需要1行,也不需要循环。
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() - 显式编码
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()
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);
}
}
}
答案 9 :(得分:0)
如果使用JDK 11(由nullpointer发布),可能还不够完整,并且可能已过时。如果您有非文件输入流,仍然有用
c.onWidget2 = function(template, task) {
c.taskName = task.short_description;
var initWidget = spUtil.get('hrj_task_activity_scoped', {
sys_id: task.sys_id,
table: 'sn_hr_core_task',
recordInfo: task.taskInfo
}).then(function(response) {
c.newTask2 = response;
});
c.modalInstance = $uibModal.open({
templateUrl: template,
scope: $scope,
size: 'lg'
}).rendered.then(initWidget);
};
//closeModal for the "x"
c.closeModal = function() {
c.modalInstance.close();
};