起航学习网

- 让每个人都能学到最前沿新知识、新技能!
起航学习网
当前位置: 起航学习网 > 短期培训 > 编程语言 > Java文件读取的方法

Java文件读取的方法

时间:2022-06-08 14:16:49来源:IT培训网 作者:Java学习网 已有: 名学员访问该课程

  快捷搜索:java文件读取

前言: 有多种写入和读取文本文件的方法。在处理许多应用程序时,这是必需的。有几种方法可以在 Java 中读取纯文本文件

有多种写入和读取文本文件的方法。在处理许多应用程序时,这是必需的。有几种方法可以在 Java 中读取纯文本文件,IT培训网小编给大家举例,如您可以使用FileReader、BufferedReader或Scanner来读取文本文件。每个实用程序都提供了一些特殊的功能,例如 BufferedReader 提供数据缓冲以便快速读取,而 Scanner 提供解析能力。

方法:

1.使用 BufferedReader 类

2.使用FileReader类

3.使用Scanner类

4.读取列表中的整个文件

5.以字符串形式读取文本文件

让我们更深入地讨论上述每种方法,最重要的是通过一个干净的 Java 程序来实现它们。

方法一:使用 BufferedReader 类

此方法从字符输入流中读取文本。它确实缓冲以有效读取字符、数组和行。可以指定缓冲区大小,也可以使用默认大小。对于大多数用途,默认值足够大。通常,由 Reader 发出的每个读取请求都会导致对底层字符或字节流发出相应的读取请求。因此,建议将 BufferedReader 包裹在 read() 操作可能成本高昂的任何 Reader 周围,例如 FileReaders 和 InputStreamReaders,如下所示:

BufferedReader in = new BufferedReader(Reader in, int size);

例子:

// Java Program to illustrate Reading from FileReader
// using BufferedReader Class
// Importing input output classes
import java.io.*;
// Main class
public class GFG {
	// main driver method
	public static void main(String[] args) throws Exception
	{
		// File path is passed as parameter
		File file = new File(
			"C:\\Users\\pankaj\\Desktop\\test.txt");
		// Note: Double backquote is to avoid compiler
		// interpret words
		// like \test as \t (ie. as a escape sequence)
		// Creating an object of BufferedReader class
		BufferedReader br
			= new BufferedReader(new FileReader(file));
		// Declaring a string variable
		String st;
		// Condition holds true till
		// there is character in a string
		while ((st = br.readLine()) != null)
			// Print the string
			System.out.println(st);
	}
}

方法二:使用 FileReader 类

读取字符文件的便利类。此类的构造函数假定默认字符编码和默认字节缓冲区大小是适当的。

该类中定义的构造函数如下:

FileReader(File file):给定要读取的文件,创建一个新的 FileReader

FileReader(FileDescriptor fd):给定要读取的 FileDescriptor,创建一个新的 FileReader

FileReader(String fileName):给定要读取的文件名,创建一个新的 FileReader

例子:

// Java Program to Illustrate reading from
// FileReader using FileReader class
// Importing input output classes
import java.io.*;
// Main class
// ReadingFromFile
public class GFG {
	// Main driver method
	public static void main(String[] args) throws Exception
	{
		// Passing the path to the file as a parameter
		FileReader fr = new FileReader(
			"C:\\Users\\pankaj\\Desktop\\test.txt");
		// Declaring loop variable
		int i;
		// Holds true till there is nothing to read
		while ((i = fr.read()) != -1)
			// Print all the content of a file
			System.out.print((char)i);
	}
}

方法 3:使用 Scanner 类

一个简单的文本扫描器,可以使用正则表达式解析原始数据类型和字符串。Scanner 使用分隔符模式将其输入分解为标记,默认情况下匹配空格。然后可以使用各种 next 方法将生成的标记转换为不同类型的值。

示例 1:使用循环

// Java Program to illustrate
// reading from Text File
// using Scanner Class
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner
{
public static void main(String[] args) throws Exception
{
	// pass the path to the file as a parameter
	File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");
	Scanner sc = new Scanner(file);
	while (sc.hasNextLine())
	System.out.println(sc.nextLine());
}
}

示例 2:不使用循环

// Java Program to illustrate reading from FileReader
// using Scanner Class reading entire File
// without using loop
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop
{
public static void main(String[] args)
						throws FileNotFoundException
{
	File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");
	Scanner sc = new Scanner(file);
	// we just need to use \\Z as delimiter
	sc.useDelimiter("\\Z");
	System.out.println(sc.next());
}
}

方法4:读取列表中的整个文件

从文件中读取所有行。此方法确保在读取所有字节或引发 I/O 错误或其他运行时异常时关闭文件。使用指定的字符集将文件中的字节解码为字符。

句法:

public static List readAllLines(Path path,Charset cs)throws IOException

此方法将以下内容识别为行终止符:

\u000D 后跟 \u000A,回车后跟 LINE FEED
\u000A,换行
\u000D,回车

例子

// Java program to illustrate reading data from file
// using nio.File
import java.util.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.io.*;
public class ReadFileIntoList
{
public static List<String> readFileInList(String fileName)
{
	List<String> lines = Collections.emptyList();
	try
	{
	lines =
	Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
	}
	catch (IOException e)
	{
	// do something
	e.printStackTrace();
	}
	return lines;
}
public static void main(String[] args)
{
	List l = readFileInList("C:\\Users\\pankaj\\Desktop\\test.java");
	Iterator<String> itr = l.iterator();
	while (itr.hasNext())
	System.out.println(itr.next());
}
}

方法5:将文本文件读取为字符串

例子

// Java Program to illustrate
// reading from text file
// as string in Java
package io;
import java.nio.file.*;;
public class ReadTextAsString {
public static String readFileAsString(String fileName)throws Exception
{
	String data = "";
	data = new String(Files.readAllBytes(Paths.get(fileName)));
	return data;
}
public static void main(String[] args) throws Exception
{
	String data = readFileAsString("C:\\Users\\pankaj\\Desktop\\test.java");
	System.out.println(data);
}
}

 

文章出自:http://qh.itpxw.cn/peixun/software/2022121585.html

文章标题:Java文件读取的方法



免责声明:本站文章均由入驻起航学习网的会员所发或者网络转载,所述观点仅代表作者本人,不代表起航学习网立场。如有侵权或者其他问题,请联系举报,必删。侵权投诉

你也许会喜欢如下的文章?
(责任编辑:深圳学历教育网)
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
培训学校
IT培训网 访问该机构站点 报名留言 加为好友 用户等级:注册会员 用户级别:10 机构名称:IT培训网 联 系 人:罗老师 联系电话:13783581536 联系手机:13783581536 在线客服:起航学习网客服 在 线 QQ:起航学习网客服 电子邮件: 网站域名:http://www.itpxw.cn 注册时间:2016-07-18 11:07 最后登录:2024-02-20 13:02
推荐内容