欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java以绝对路径和相对路径的方式读取文件

程序员文章站 2022-05-09 23:50:18
...

1. 绝对路径的方式读取文件

这个很简单,就是用大家熟悉的File类加载文件,然后用输入流读取文件内容就可以了。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ReadFileTest {
	public static void main(String[] args) {
		String filename = "E:\\code\\ndctest\\src\\file\\test.txt";
		ReadFileTest readFileTest = new ReadFileTest();
		System.out.println(readFileTest.readTxt(filename));
	}

	/**
	 * 读取绝对路径文件
	 * @param filename
	 * @return
	 */
	public String readTxt(String filename) {
		File file = new File(filename);
		StringBuilder sb = new StringBuilder();
		try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");) {
			if (file.isFile() && file.exists()) {
				BufferedReader bufferedReader = new BufferedReader(read);
				String readLine = null;
				while ((readLine = bufferedReader.readLine()) != null) {
					sb.append(readLine);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("xml数据读取错误");
		}
		return sb.toString();
	}

2. 相对路径的方式读取文件

这个其实也很简单,用到的是Class类的getResourceAsStream(String name)这个方法,返回值直接就是InputStream类型。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ReadFileTest {
	public static void main(String[] args) {
		ReadFileTest readFileTest = new ReadFileTest();
		String filename2 = "file/test.txt";
		System.out.println(readFileTest.readTxt2(filename2));
	}

	/**
	 * 读取相对路径文件
	 * @param filename
	 * @return
	 */
	public String readTxt2(String filename){
		StringBuilder sb = new StringBuilder();
		try (InputStream is = this.getClass().getResourceAsStream(filename);
				InputStreamReader reader = new InputStreamReader(is, "UTF-8");
				BufferedReader bufferedReader = new BufferedReader(reader);) {
			String readLine = null;
			while ((readLine = bufferedReader.readLine()) != null) {
				sb.append(readLine);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("xml数据读取错误");
		}
		return sb.toString();
	}
}