用Java读取文件的5种方法-BufferedReader,FileInputStream,Files,Scanner,RandomAccessFile
时间:2020-02-23 14:35:32 来源:igfitidea点击:
有许多不同的方法来读取Java文件。
在本教程中,我们将研究5种不同的方式来读取Java文件。
用Java读取文件的不同方法
Java IO API中用于读取文件的5个类是:
- 缓冲读取器
- FileInputStream
- 档案
- 扫描器
- 随机存取文件
读取二进制文件与文本文件
FileInputStream类将文件数据读入字节流。
因此,应将其用于二进制文件,例如图像,pdf,媒体,视频等。文本文件是基于字符的。
我们可以使用Reader类以及Stream类来读取它们。文件和扫描程序类可用于读取文本文件,而不是二进制文件。
让我们看一下示例程序,以Java读取文件。
1. BufferedReader读取文件
我们可以使用BufferedReader将文本文件内容读取到char数组中。
BufferedReader可以高效地读取文件,因为它可以缓冲来自指定文件的输入。
如果不进行缓冲,则每次调用read()或者readLine()方法都会从文件中读取字节,然后将其转换为字符并返回,这将非常低效。
package com.theitroad.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/hyman/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();
}
}
}
在上面的程序中,我正在将文件数据打印到控制台。
让我们看另一种执行读取文件操作的实用程序类。
- 以字符串形式读取完整文件
- 逐行读取文件并返回String列表
- 计算给定文件中字符串的出现。
package com.theitroad.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/hyman/Downloads/myfile.txt";
String str="Java";
String fileData = readCompleteFileAsString(filePath);
System.out.println("Complete File Data:"+fileData);
List<String> linesData = readFileToListOfLines(filePath);
if(linesData!=null){
for(int i=0; i<linesData.size(); i++){
System.out.println("Line "+i+": "+linesData.get(i));
}
}
int count = countStringInFile(filePath,str);
System.out.println("String "+str+" found "+count+" times in the given file");
}
/**
* This function will count the number of times given String appears in the file
* @param filePath
* @param string
* @return
*/
private static int countStringInFile(String filePath, String str) {
if(filePath == null || filePath == "" || str == null || str == "") return 0;
int count=0;
int searchStrLength = str.length();
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 0;
}
String line;
try {
while ((line=reader.readLine()) != null) {
for(int i=0;i<line.length();) {
int index=line.indexOf(str,i);
if(index!=-1) {
count++;
i+=index+searchStrLength;
} else {
break;
}
}
}
} catch (IOException e) {
System.out.println("IOException in reading data from file.");
return 0;
}
try {
reader.close();
} catch (IOException e) {
System.out.println("IOException in closing the Buffered Reader.");
return count;
}
return count;
}
/**
* This function will read file line by line and return the data in form of a list of String
* @param filePath
* @return
*/
private static List<String> readFileToListOfLines(String filePath) {
List<String> linesData = new ArrayList<String>();
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 –将二进制文件读取为字节
我们应该始终使用Stream来读取非基于字符的文件,例如图像,视频等。
package com.theitroad.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/hyman/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();
}
}
}
FileInputStream读操作用于字节数组,而BufferedReader读操作使用char数组。
3.文件–将文件读取到字符串列表
文件是Java 1.7发行版中引入的实用程序类。
我们可以使用它的readAllLines()方法读取文本文件数据作为字符串列表。
package com.theitroad.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<String> allLines = Files.readAllLines(Paths.get("/Users/hyman/Downloads/myfile.txt"));
for (String line : allLines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.扫描仪–以迭代器读取文本文件
我们可以使用Scanner类读取文本文件。
它可以作为迭代器
package com.theitroad.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/hyman/Downloads/myfile.txt"));
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
5. RandomAccessFile –以只读模式读取文件
RandomAccessFile类允许我们以不同的模式读取文件。
当您要确保对文件不执行意外写入操作时,这是一个不错的选择。
package com.theitroad.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/hyman/Downloads/myfile.txt", "r");
String str;
while ((str = file.readLine()) != null) {
System.out.println(str);
}
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

