本文共 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文件。
The 5 classes from the Java IO API to read files are:
Java IO API中用于读取文件的5个类是:
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,媒体,视频等。 Reader
classes as well as Stream classes to read them. 文本文件是基于字符的。 我们可以使用Reader
类以及Stream类来读取它们。 Let’s look into the example programs to read a file in Java.
让我们看一下示例程序以Java读取文件。
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.
在上面的程序中,我正在将文件数据打印到控制台。 让我们看看另一个执行读取文件操作的实用程序类。
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); ListlinesData = 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(); }}
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数组。
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 { ListallLines = Files.readAllLines(Paths.get("/Users/pankaj/Downloads/myfile.txt")); for (String line : allLines) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } }}
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(); } }}
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/