Java读取本地文件内容并输出

下面是读取本地文件并输出内容的Java代码。
如果文件有中文,可能会乱码需要设置软件的编码格式。

	public static void readFile() {
		FileReader fileReader = null;
		BufferedReader br = null;
		String line = null;
		try {
			// Target file path
			File testFile = new File("E:\\Test_JAVAProgram\\TestReadFile\\file.txt");
			if(!testFile.exists()) {
				System.out.println(testFile.getName() + " isn't existed");
			}
			// Read target file
			fileReader = new FileReader(testFile);
			br = new BufferedReader(fileReader);
			line = br.readLine();
			while(line != null) {
				System.out.println(line);
				// Notice: the following statement is necessary.
				line = br.readLine();
			}
		}catch(Exception e) {
			e.toString();
		}
		finally {
			if(br != null) {
				try {
					br.close();
				}catch(Exception e) {
					e.toString();
					br = null;
				}
			}
			if(fileReader != null) {
				try {
					fileReader.close();
				}catch(Exception e) {
					e.toString();
				}
			}
		}
	}

while(line != null) {
System.out.println(line);
// Notice: the following statement is necessary.
line = br.readLine();
}
这里highlight出来的这一行代码,是需要注意的。没有这行代码会死循环。

2021-9-4更新
使用try-resource方式,它可以帮助我们close实现了
AutoCloseable方法的对象。

public static void main(String[] args) throws FileNotFoundException {
        readFile();
    }

    public static void readFile() throws FileNotFoundException {
        String line;
        File testFile = new File("E:\\JAVAProgram\\TestReadFile\\file.txt");
        if(!testFile.exists()) {
            System.out.println(testFile.getName() + " isn't existed");
            throw new FileNotFoundException(testFile.getName() + " is not found");
        }
        // 使用try-resource方式
        try (FileReader fileReader = new FileReader(testFile); BufferedReader br = new BufferedReader(fileReader)) {
            line = br.readLine();
            while(line != null) {
                System.out.println(line);
                // Notice: the following statement is necessary.
                line = br.readLine();
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(读取本地文件内容,java)