[英]How can I read and work on a textual file starting from its path in Java?
I have the following task that have to be implemented in Java.我有以下必须在 Java 中实现的任务。
I have a String that represent the path of a txt file, something like this:我有一个表示txt文件路径的字符串,如下所示:
String fileFatturePa = "C:\\Users\\Andrea\\Desktop\\D150316.T1642\\myFile.txt";
This textual file contains some text (that represent XML but this is not important because I do not have to operate on it with something like XPath but I have to do simple substring operation).这个文本文件包含一些文本(代表 XML 但这并不重要,因为我不必使用 XPath 之类的东西对其进行操作,但我必须执行简单的子字符串操作)。
So I need to read this textual file (starting from its path) and then I have to do some textual operation.所以我需要读取这个文本文件(从它的路径开始),然后我必须做一些文本操作。
This file could be very big.这个文件可能非常大。
What is the best way to read it stargint from its path?从路径开始阅读它的最佳方法是什么?
一个好的起点是 Oracle 的官方 Java 文档: Basic I/O 。
BufferedReader reader = new BufferedReader(new FileReader(fileFatturePa));
try
{
String line = null;
while ((line = reader.readLine()) != null)
{
***operations(specific to each line of the text file) ***
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
reader.close();
}
Simple, you create a new File: File f = new File(path)
.很简单,您创建一个新文件: File f = new File(path)
。 For raed all the lines, you can use the class Fileutils from Apache Commons IO.对于所有行,您可以使用 Apache Commons IO 中的 Fileutils 类。 And you will have something like: List<String> allLines=Fileutils.readlines(f)
你会得到类似的东西: List<String> allLines=Fileutils.readlines(f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.