博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java 读取文件文本内容_Java读取文本文件
阅读量:2531 次
发布时间:2019-05-11

本文共 8950 字,大约阅读时间需要 29 分钟。

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

    Java使用读取文本文件
  2. Read text file in java using

    使用读取Java中的文本文件
  3. Java read text file using

    Java使用读取文本文件
  4. Using to read text file in java

    使用读取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
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 line    System.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 line     System.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 , Scanner is the class to use.

如果要逐行或基于某些读取文件,则使用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 linewhile(scanner.hasNextLine()){    //process each line    String 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 data        readUsingFiles(fileName);                //using Scanner class for large files, to read line by line        readUsingScanner(fileName);                //read using BufferedReader, to read line by line        readUsingBufferedReader(fileName);        readUsingBufferedReaderJava7(fileName, StandardCharsets.UTF_8);        readUsingBufferedReader(fileName, StandardCharsets.UTF_8);                //read using FileReader, no encoding support, not efficient        readUsingFileReader(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 line            System.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 line            System.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 line            System.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 line            System.out.println(line);        }        //close resources        br.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 line        while(scanner.hasNextLine()){            //process each line            String 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 array        byte[] bytes = Files.readAllBytes(path);        System.out.println("Read text file using Files class");        //read file to String list        @SuppressWarnings("unused")		List
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 . We can use this to read text file in java.

在结束本教程之前,我想谈谈 。 我们可以使用它来读取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读取文本文件示例程序就这些了。

翻译自:

java 读取文件文本内容

转载地址:http://zqozd.baihongyu.com/

你可能感兴趣的文章
JSP开发模式
查看>>
我的Android进阶之旅------>Android嵌入图像InsetDrawable的使用方法
查看>>
Detours信息泄漏漏洞
查看>>
win32使用拖放文件
查看>>
Android 动态显示和隐藏软键盘
查看>>
raid5什么意思?怎样做raid5?raid5 几块硬盘?
查看>>
【转】how can i build fast
查看>>
null?对象?异常?到底应该如何返回错误信息
查看>>
django登录验证码操作
查看>>
(简单)华为Nova青春 WAS-AL00的USB调试模式在哪里开启的流程
查看>>
图论知识,博客
查看>>
[原创]一篇无关技术的小日记(仅作暂存)
查看>>
20145303刘俊谦 Exp7 网络欺诈技术防范
查看>>
原生和jQuery的ajax用法
查看>>
iOS开发播放文本
查看>>
20145202马超《java》实验5
查看>>
JQuery 事件
查看>>
main(argc,argv[])
查看>>
在线教育工具—白板系统的迭代1——bug监控排查
查看>>
121. Best Time to Buy and Sell Stock
查看>>