Java按行读取文件内容:简要方法介绍和实例演示

Java 按行读取文件内容:简要方法介绍和实例演示

1、使用到的相关方法和类简介

public FileInputStream(File file) throws FileNotFoundException
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system. A new FileDescriptor object is created to represent this file connection.
If the named file does not exist, is a directory rather than a regular
file, or for some other reason cannot be opened for reading then a
FileNotFoundException is thrown.

Parameters:
file - the file to be opened for reading.
Throws:
FileNotFoundException - if the file does not exist, is a directory
rather than a regular file, or for some other reason cannot be opened
for reading. SecurityException - if a security manager exists and its
checkRead method denies read access to the file.

这是查阅的java原始库中的描述,简单介绍就是传入参数file,试图通过关联一个具体的文件建立一个文件输入流,如果文件名字不存在、无法被打开或是无法被阅读,那么就抛出异常。

建立文件输入流后,进一步需要建立BufferedReader对象来对文件输入进行读取。以下给出java原文档给出的实例,其中传入BufferedReader的参数还可以是InputStreamReader等输入流。

BufferedReader in
= new BufferedReader(new FileReader(“foo.in”));

建立好字符读入后,便可以调用其中的方法进行按行读取内容。这里主要给出一个之后需要用到的方法,也就是按行读取一个字符串。

String readLine() Reads a line of text.

2、实例演示

		File fileInput = new File(fileName);
		ArrayList<ArrayList<Integer>> input = new ArrayList<ArrayList<Integer>>();
		String str = new String();
		int i = 0;
		try {
			FileInputStream file = new FileInputStream(fileInput);
			BufferedReader br = new BufferedReader(new InputStreamReader(file, "UTF-8"));// 构造一个BufferedReader类来读取文件
			while ((str = br.readLine()) != null) {
				ArrayList<Integer> e = new ArrayList<Integer>();
				input.add(e);
				// System.out.println(str);
				for (String a : str.split("\t")) {
					try {
						if(Integer.parseInt(a)<0)
						{
							System.out.println("输入中含有负数");
							return null;
						}
						input.get(i).add(Integer.parseInt(a));
					} catch (Exception w) {
						System.out.println("非法输入格式或内容");
						return null;
					}
				}
				i++;
			}
		} catch (Exception e) {
			System.out.println("读入文件错误");
			return null;
		}

这段代码处理的是读取文件中的不含负数和小数的矩阵,按行对矩阵进行处理,最终将矩阵保存在input中,方便后续进一步处理。代码中的fileName便是读入文件的路径。


版权声明:本文为new_sailor原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。