用于在Java中读取文件的最佳/最简单的类是什么?
我对简单的线条处理感兴趣。
扫描器:
for(Scanner sc = new Scanner(new File("my.file")); sc.hasNext(); ) { String line = sc.nextLine(); ... // do something with line }
看一下Scanner类。
它在Java 5中添加,使得读取字符串和文件比旧的FileReaders和FileInputStream链更容易(不再需要new BufferedReader(new FileReader())
来获取readLine
方法)。
在Scanner类中,您可以使用nextLine
方法一次读取一行,但它也有许多用于在文件中查找基元和正则表达式的util方法。
您可以使用BufferedReader
,如下所示: –
try { BufferedReader input = new BufferedReader(new FileReader(new File("c:\\test.txt"))); try { String line = null; while ((line = input.readLine()) != null) { System.out.println(line); } } finally { input.close(); } } catch (IOException ex) { ex.printStackTrace(); }
如果您愿意使用第三方库 ,那么实用程序类(例如来自Guava的 Files
或来自Apache Commons IO的 FileUtils
会使读取文件变得非常简单。
下面的示例(其中File file = new File("path/to/file.txt")
)将文本文件的所有行读入List,并将整个文件读入String。
番石榴:
List lines = Files.readLines(file, Charsets.UTF_8); String contents = Files.toString(file, Charsets.UTF_8);
Apache Commons IO:
List lines = FileUtils.readLines(file, "UTF-8"); String contents = FileUtils.readFileToString(file, "UTF-8")
我的建议(截至2013年)是Guava ,这是一个现代化,干净,积极维护的图书馆。 它通常比Apache Commons的质量更高。
当然,为此添加番石榴是没有意义的,因为它是一个相对较大的库。 另一方面,今天在Java项目中不使用Guava会让IMO变得愚蠢。 🙂
诚然,JDK现在为此特定目的提供了一些适当的工具( 扫描仪 ); 使用第三方库来读取文件更合理,因为这样的东西是另类。
Apache commons始终是一个很好的起点。
见http://commons.apache.org/io/
你可以试试apache的FileUtils。 方法如
for(String line: FileUtils.readLines(file)) { System.out.println(line); }
您还可以使用包装在BufferedReader中的InputStreamReader(使用InputStream创建,如FileInputStream)来简单地读取文件。