Java reads the contents of a local file and outputs

Below is the Java code to read the local file and output the content.
If the file is in Chinese, it may be garbled and you need to set the encoding format of the software.

	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(); } The line of code highlighted here needs attention. Without this line of code, there will be an endless loop.




Guess you like

Origin blog.csdn.net/weixin_42488909/article/details/108805109