博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用Java读取文件的5种方法-BufferedReader,FileInputStream,文件,扫描仪,RandomAccessFile
阅读量:2529 次
发布时间:2019-05-11

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

There are many different ways to read a file in Java. In this tutorial, we will look into 5 different ways to read a file in Java.

有许多不同的方法来读取Java文件。 在本教程中,我们将研究5种不同的方式来读取Java文件。

用Java读取文件的不同方法 (Different Ways to Read a File in Java)

The 5 classes from the Java IO API to read files are:

Java IO API中用于读取文件的5个类是:

  1. BufferedReader

    缓冲读取器
  2. FileInputStream

    FileInputStream
  3. Files

    档案
  4. Scanner

    扫描器
  5. RandomAccessFile

    随机存取文件

读取二进制文件与文本文件 (Reading Binary Files vs Text Files)

  • The FileInputStream class reads the file data into a stream of bytes. So it should be used for binary files such as image, pdf, media, videos, etc.

    FileInputStream类将文件数据读取到字节流中。 因此,应将其用于二进制文件,例如图像,pdf,媒体,视频等。
  • Text files are character based. We can use Reader classes as well as Stream classes to read them.

    文本文件是基于字符的。 我们可以使用Reader类以及Stream类来读取它们。
  • Files and Scanner classes can be used to read text files, not binary files.

    文件和扫描程序类可用于读取文本文件,而不是二进制文件。

Let’s look into the example programs to read a file in Java.

让我们看一下示例程序以Java读取文件。

1. BufferedReader读取文件 (1. BufferedReader Read File)

We can use BufferedReader to read the text file contents into .

我们可以使用BufferedReader将文本文件内容读取到 。

is efficient for reading the file because it buffers the input from the specified file. Without buffering, each invocation of the read() or readLine() methods will read bytes from the file, then converted into characters and returned, which will be very inefficient.

对于读取文件非常有效,因为它会缓冲来自指定文件的输入。 如果不进行缓冲,则每次调用read()或readLine()方法都会从文件中读取字节,然后转换为字符并返回,这将非常低效。

package com.journaldev.io.readfile;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class ReadFileUsingBufferedReader {	public static void main(String[] args) {		BufferedReader reader;		char[] buffer = new char[10];		try {			reader = new BufferedReader(new FileReader(					"/Users/pankaj/Downloads/myfile.txt"));			while (reader.read(buffer) != -1) {				System.out.print(new String(buffer));				buffer = new char[10];			}			reader.close();		} catch (IOException e) {			e.printStackTrace();		}	}}

In the above program, I am printing the file data to console. Let’s look at another utility class to perform read file operations.

在上面的程序中,我正在将文件数据打印到控制台。 让我们看看另一个执行读取文件操作的实用程序类。

  1. Read complete file as String

    以字符串形式读取完整文件
  2. Read file line by line and return list of String

    逐行读取文件并返回String列表
  3. Count the occurrence of a String in the given file.

    计算给定文件中字符串的出现。
package com.journaldev.java;import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List;public class ReadFileJavaExample {	/**	 * Main function to invoke different functions to	 * 1. readCompleteFileAsString - Read complete file as String	 * 2. readFileToListOfLines - Read lines from file and return list of line String	 * 3. countStringInFile - Count occurrence of a String in the file	 * @param args	 */	public static void main(String[] args) {		String filePath = "/Users/pankaj/Downloads/myfile.txt";		String str="Java";		String fileData = readCompleteFileAsString(filePath);		System.out.println("Complete File Data:"+fileData);		List
linesData = readFileToListOfLines(filePath); if(linesData!=null){ for(int i=0; i
readFileToListOfLines(String filePath) { List
linesData = new ArrayList
(); BufferedReader reader; try { reader = new BufferedReader( new FileReader(filePath)); } catch (FileNotFoundException e) { System.out.println("File is not present in the classpath or given location."); return null; } String line; try { while ((line=reader.readLine()) != null) { linesData.add(line); } } catch (IOException e) { System.out.println("IOException in reading data from file."); return null; } try { reader.close(); } catch (IOException e) { System.out.println("IOException in closing the Buffered Reader."); return null; } return linesData; } /** * This function will read complete file and return it as String * @param filePath * @return */ private static String readCompleteFileAsString(String filePath) { StringBuilder fileData = new StringBuilder(); BufferedReader reader; try { reader = new BufferedReader( new FileReader(filePath)); } catch (FileNotFoundException e) { System.out.println("File is not present in the classpath or given location."); return null; } char[] buf = new char[1024]; int numRead=0; try { while((numRead=reader.read(buf)) != -1){ String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } } catch (IOException e) { System.out.println("IOException in reading data from file."); return null; } try { reader.close(); } catch (IOException e) { System.out.println("IOException in closing the Buffered Reader."); return null; } return fileData.toString(); }}

2. FileInputStream –将二进制文件读取为字节 (2. FileInputStream – Read Binary Files to Bytes)

We should always use Stream for reading non-character based files such as image, videos, etc.

我们应该始终使用Stream来读取非基于字符的文件,例如图像,视频等。

package com.journaldev.io.readfile;import java.io.FileInputStream;import java.io.IOException;public class ReadFileUsingFileInputStream {	public static void main(String[] args) {		FileInputStream fis;		byte[] buffer = new byte[10];		try {			fis = new FileInputStream("/Users/pankaj/Downloads/myfile.txt");			while (fis.read(buffer) != -1) {				System.out.print(new String(buffer));				buffer = new byte[10];			}			fis.close();		} catch (IOException e) {			e.printStackTrace();		}	}}

The read operation is used with whereas BufferedReader read operation uses char array.

读操作用于而BufferedReader读操作使用char数组。

3.文件–将文件读取到字符串列表 (3. Files – Read File to List of Strings)

is a utility class that was introduced in Java 1.7 release. We can use its readAllLines() method to read text file data as a of string.

是Java 1.7发行版中引入的实用程序类。 我们可以使用它的readAllLines()方法来读取文本文件数据作为字符串 。

package com.journaldev.io.readfile;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Paths;import java.util.List;public class ReadFileUsingFiles {	public static void main(String[] args) {		try {			List
allLines = Files.readAllLines(Paths.get("/Users/pankaj/Downloads/myfile.txt")); for (String line : allLines) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } }}

4.扫描仪–以迭代器读取文本文件 (4. Scanner – Read Text File as Iterator)

We can use to read text file. It works as an iterato

我们可以使用读取文本文件。 它可以作为迭代器

package com.journaldev.io.readfile;import java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;public class ReadFileUsingScanner {	public static void main(String[] args) {		try {			Scanner scanner = new Scanner(new File("/Users/pankaj/Downloads/myfile.txt"));			while (scanner.hasNextLine()) {				System.out.println(scanner.nextLine());			}			scanner.close();		} catch (FileNotFoundException e) {			e.printStackTrace();		}	}}

5. RandomAccessFile –以只读模式读取文件 (5. RandomAccessFile – Reading Files in Read-Only Mode)

The class allows us to read file in different modes. It’s a good option when you want to make sure that no accidental write operation is performed on the file.

类允许我们以不同的模式读取文件。 当您要确保对文件不执行任何意外的写操作时,这是一个不错的选择。

package com.journaldev.io.readfile;import java.io.IOException;import java.io.RandomAccessFile;public class ReadFileUsingRandomAccessFile {	public static void main(String[] args) {		try {			RandomAccessFile file = new RandomAccessFile("/Users/pankaj/Downloads/myfile.txt", "r");			String str;			while ((str = file.readLine()) != null) {				System.out.println(str);			}			file.close();		} catch (IOException e) {			e.printStackTrace();		}	}}

That’s all for reading a file in Java using various classes from Java IO API.

这就是使用Java IO API中的各种类来读取Java文件的全部方法。

. 下载所有示例代码。

References:

参考文献:

翻译自:

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

你可能感兴趣的文章
Thrift源码分析(二)-- 协议和编解码
查看>>
考勤系统之计算工作小时数
查看>>
4.1 分解条件式
查看>>
Equivalent Strings
查看>>
flume handler
查看>>
收藏其他博客园主写的代码,学习加自用。先表示感谢!!!
查看>>
H5 表单标签
查看>>
su 与 su - 区别
查看>>
C语言编程-9_4 字符统计
查看>>
在webconfig中写好连接后,在程序中如何调用?
查看>>
限制用户不能删除SharePoint列表中的条目(项目)
查看>>
【Linux网络编程】使用GDB调试程序
查看>>
feign调用spring clound eureka 注册中心服务
查看>>
ZT:Linux上安装JDK,最准确
查看>>
LimeJS指南3
查看>>
关于C++ const成员的一些细节
查看>>
《代码大全》学习摘要(五)软件构建中的设计(下)
查看>>
C#检测驱动是否安装的问题
查看>>
web-4. 装饰页面的图像
查看>>
微信测试账户
查看>>