java 读取文件文本内容

There are many ways to read a text file in java. Let’s look at java read text file different methods one by one.

有许多方法可以读取Java中的文本文件。 让我们一一看一下Java读取文本文件的不同方法。

Java读取文本文件 (Java read text file)

There are many ways to read a text file in java. A text file is made of characters, so we can use Reader classes. There are some utility classes too to read a text file in java.

有许多方法可以读取Java中的文本文件。 文本文件由字符组成,因此我们可以使用Reader类。 也有一些实用程序类可以读取Java中的文本文件。

  1. Java read text file using Files classJava使用Files类读取文本文件
  2. Read text file in java using FileReader使用FileReader读取Java中的文本文件
  3. Java read text file using BufferedReaderJava使用BufferedReader读取文本文件
  4. Using Scanner class to read text file in java使用Scanner类读取Java中的文本文件

Now let’s look at examples showing how to read a text file in java using these classes.

现在,让我们看一些示例,这些示例说明如何使用这些类在Java中读取文本文件。

Java使用java.nio.file.Files读取文本文件 (Java read text file using java.nio.file.Files)

We can use Files class to read all the contents of a file into a byte array. Files class also has a method to read all lines to a list of string. Files class is introduced in Java 7 and it’s good if you want to load all the file contents. You should use this method only when you are working on small files and you need all the file contents in memory.

我们可以使用Files类将文件的所有内容读入字节数组。 Files类还具有一种读取所有行到字符串列表的方法。 Files类是Java 7中引入的,如果要加载所有文件内容,则很好。 仅在处理小型文件并且需要所有文件内容在内存中时,才应使用此方法。

String fileName = "/Users/pankaj/source.txt";
Path path = Paths.get(fileName);
byte[] bytes = Files.readAllBytes(path);
List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);

使用java.io.FileReader在Java中读取文本文件 (Read text file in java using java.io.FileReader)

You can use FileReader to get the BufferedReader and then read files line by line. FileReader doesn’t support encoding and works with the system default encoding, so it’s not a very efficient way of reading a text file in java.

您可以使用FileReader获取BufferedReader,然后逐行读取文件。 FileReader不支持编码,并且与系统默认编码一起使用,因此,这不是在Java中读取文本文件的非常有效的方法。

String fileName = "/Users/pankaj/source.txt";
File file = new File(fileName);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null){//process the lineSystem.out.println(line);
}

Java使用java.io.BufferedReader读取文本文件 (Java read text file using java.io.BufferedReader)

BufferedReader is good if you want to read file line by line and process on them. It’s good for processing the large file and it supports encoding also.

如果要逐行读取文件并对其进行处理,则BufferedReader很好。 这对于处理大文件非常有用,并且还支持编码。

BufferedReader is synchronized, so read operations on a BufferedReader can safely be done from multiple threads. BufferedReader default buffer size is 8KB.

BufferedReader是同步的,因此可以安全地从多个线程完成对BufferedReader的读取操作。 BufferedReader的默认缓冲区大小为8KB。

String fileName = "/Users/pankaj/source.txt";
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, cs);
BufferedReader br = new BufferedReader(isr);String line;
while((line = br.readLine()) != null){//process the lineSystem.out.println(line);
}
br.close();

使用扫描仪读取Java中的文本文件 (Using scanner to read text file in java)

If you want to read file line by line or based on some java regular expression, Scanner is the class to use.

如果要逐行或基于某些Java正则表达式读取文件,则使用Scanner类。

Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. The scanner class is not synchronized and hence not thread safe.

扫描程序使用定界符模式将其输入分为令牌,默认情况下,该模式与空格匹配。 然后,可以使用各种下一种方法将生成的令牌转换为不同类型的值。 扫描器类未同步,因此不是线程安全的。

Path path = Paths.get(fileName);
Scanner scanner = new Scanner(path);
System.out.println("Read text file using Scanner");
//read line by line
while(scanner.hasNextLine()){//process each lineString line = scanner.nextLine();System.out.println(line);
}
scanner.close();

Java读取文件示例 (Java Read File Example)

Here is the example class showing how to read a text file in java. The example methods are using Scanner, Files, BufferedReader with Encoding support and FileReader.

这是显示如何在Java中读取文本文件的示例类。 示例方法使用的是Scanner,Files,具有编码支持的BufferedReader和FileReader。

package com.journaldev.files;import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;public class JavaReadFile {public static void main(String[] args) throws IOException {String fileName = "/Users/pankaj/source.txt";//using Java 7 Files class to process small files, get complete file datareadUsingFiles(fileName);//using Scanner class for large files, to read line by linereadUsingScanner(fileName);//read using BufferedReader, to read line by linereadUsingBufferedReader(fileName);readUsingBufferedReaderJava7(fileName, StandardCharsets.UTF_8);readUsingBufferedReader(fileName, StandardCharsets.UTF_8);//read using FileReader, no encoding support, not efficientreadUsingFileReader(fileName);}private static void readUsingFileReader(String fileName) throws IOException {File file = new File(fileName);FileReader fr = new FileReader(file);BufferedReader br = new BufferedReader(fr);String line;System.out.println("Reading text file using FileReader");while((line = br.readLine()) != null){//process the lineSystem.out.println(line);}br.close();fr.close();}private static void readUsingBufferedReader(String fileName, Charset cs) throws IOException {File file = new File(fileName);FileInputStream fis = new FileInputStream(file);InputStreamReader isr = new InputStreamReader(fis, cs);BufferedReader br = new BufferedReader(isr);String line;System.out.println("Read text file using InputStreamReader");while((line = br.readLine()) != null){//process the lineSystem.out.println(line);}br.close();}private static void readUsingBufferedReaderJava7(String fileName, Charset cs) throws IOException {Path path = Paths.get(fileName);BufferedReader br = Files.newBufferedReader(path, cs);String line;System.out.println("Read text file using BufferedReader Java 7 improvement");while((line = br.readLine()) != null){//process the lineSystem.out.println(line);}br.close();}private static void readUsingBufferedReader(String fileName) throws IOException {File file = new File(fileName);FileReader fr = new FileReader(file);BufferedReader br = new BufferedReader(fr);String line;System.out.println("Read text file using BufferedReader");while((line = br.readLine()) != null){//process the lineSystem.out.println(line);}//close resourcesbr.close();fr.close();}private static void readUsingScanner(String fileName) throws IOException {Path path = Paths.get(fileName);Scanner scanner = new Scanner(path);System.out.println("Read text file using Scanner");//read line by linewhile(scanner.hasNextLine()){//process each lineString line = scanner.nextLine();System.out.println(line);}scanner.close();}private static void readUsingFiles(String fileName) throws IOException {Path path = Paths.get(fileName);//read file to byte arraybyte[] bytes = Files.readAllBytes(path);System.out.println("Read text file using Files class");//read file to String list@SuppressWarnings("unused")List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);System.out.println(new String(bytes));}}

The choice of using a Scanner or BufferedReader or Files to read file depends on your project requirements. For example, if you are just logging the file, you can use Files and BufferedReader. If you are looking to parse the file based on a delimiter, you should use Scanner class.

使用Scanner或BufferedReader或Files读取文件的选择取决于您的项目要求。 例如,如果您仅记录文件,则可以使用“文件”和“ BufferedReader”。 如果要基于定界符解析文件,则应使用Scanner类。

Before I end this tutorial, I want to mention about RandomAccessFile. We can use this to read text file in java.

在结束本教程之前,我想谈谈RandomAccessFile 。 我们可以使用它来读取Java中的文本文件。

RandomAccessFile file = new RandomAccessFile("/Users/pankaj/Downloads/myfile.txt", "r");
String str;while ((str = file.readLine()) != null) {System.out.println(str);
}
file.close();

That’s all for java read text file example programs.

Java读取文本文件示例程序就这些了。

翻译自: https://www.journaldev.com/867/java-read-text-file

java 读取文件文本内容

java 读取文件文本内容_Java读取文本文件相关推荐

  1. java读取文件指定内容_Java读取文本指定的某一行内容

    Java读取文本指定的某一行内容,使用的都是IO的方法,下面具体看例子: /** * @author:罗大锤 * @date: 2017年9月6日 下午2:35:43 * @version 1.0 * ...

  2. Java如何读取文件文本内容的几种方式汇总

    本文为joshua317原创文章,转载请注明:转载自joshua317博客 Java如何读取文件文本内容的几种方式汇总 - joshua317的博客 package com.joshua317;imp ...

  3. js解压.gz .tar .tar.gz .zip等压缩文件(另读取文件文本内容)

    .gz 1.先把文件.文件流转换成需要的ArrayBuffer格式: //单独封装的 //此处files可以是[接口返回的文件流],也可以是input选择的文件信息中e.target.files // ...

  4. java读取文件并输出_java读取txt文件并输出结果

    这篇文章主要介绍了java读取txt文件并输出结果,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 描述: 1.java读取指定txt文件并解析 文件 ...

  5. java读取文件到字符串_Java读取文件到字符串

    java读取文件到字符串 Sometimes while working with files, we need to read the file to String in Java. Today w ...

  6. java读取文件是乱码_java读取txt文件乱码解决方案

    因为txt默认的选项是ANSI,即GBK编码.GBK和GB2312都是中文编码,在这里解释一下两者的区别. 总体说来,GBK包括所有的汉字,包括简体和繁体.而gb2312则只包括简体汉字. GBK: ...

  7. java遍历文件和归类_java读取文件的两种方法:java.io和java.lang.ClassLoader

    java读取文件的两种方法:java.io和java.lang.ClassLoader 什么时候使用java.io,什么时候使用java.lang.ClassLoader呢? (注:要是之前读xml文 ...

  8. java复制屏幕文本内容_java实现文本复制功能

    本文实例为大家分享了java实现文本复制的具体代码,供大家参考,具体内容如下 *字符流(读,写) *缓冲字符流(读,写) 文本复制功能: package cn.yunhe.io; import jav ...

  9. java搜索文本内容_JAVA 搜索文本文件中的关键字

    原文链接:http://blog..net/blog_abel/article/details/40858245 用JAVA实现对文本文件中的关键字进行搜索, 依据每一行,得到每一行中出现关键词的个数 ...

最新文章

  1. c语言程序设计 赵宏,C语言程序设计(模块化程序设计I )(6页)-原创力文档...
  2. 每日一皮:一直认为写代码的自己有点小帅
  3. HDU1862 EXCEL排序【排序】
  4. python羊车门问题_羊车门问题的python模拟和解释
  5. java 创建线程_【80期】说出Java创建线程的三种方式及对比
  6. c语言编程函数补充上机题,2011年计算机二级C语言上机操作题及答案(10)
  7. iperf3使用方法说明
  8. PTA程序设计第六周
  9. python怎么爬取新浪微博数据_新浪微博爬虫,用python爬取新浪微博数据
  10. 中国裁判文书网(2020最新版)
  11. R中设置图形参数--函数par()详解
  12. 过7游戏c语言,C语言实现扫雷小游戏
  13. 如何在excel中输入身份证号
  14. react 组件封装原则_React 组件封装
  15. python lncrna_一文解决TCGA任意肿瘤的差异lncRNA,miRNA,mRNA
  16. 孩子长高应该吃什么呢?
  17. Java 判断当前日期是否 是这个月的最后七天且是否为工作日(星期一到星期五)
  18. ArcGIS9为栅格数据管理提供了一个完整的系统
  19. vue 修复ie浏览器兼容性bug
  20. 博云容器云、DevOps 平台斩获可信云“技术最佳实践奖”

热门文章

  1. trunc函数的用法
  2. win32gui激活、关闭窗口方法
  3. 同步推软件:查看ios设备中persistentDataPath下文件,安装ipa
  4. async/await的基础用法
  5. word/ppt插入操作
  6. linux 上安装ffmpeg
  7. 4.8 对齐和混合脸部元素
  8. 英雄联盟手游赛事非常火爆电竞从业者有何不同
  9. 原码、反码、补码和移码
  10. 网迅科技加入龙蜥社区,共筑网络信息安全长城