本文共 1180 字,大约阅读时间需要 3 分钟。
读取文本文件的步骤
文件处理步骤
FileInputStream fis = new FileInputStream("file.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8)); while(true) { String line = reader.readLine(); if(line == null) break; System.out.println(line); } reader.close(); fis.close();
参数说明
文件路径为"file.txt",传输编码方式为UTF-8。本文将介绍如何通过Java读取文本文件中的内容。
异常处理
try { FileInputStream fis = new FileInputStream("file.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8)); while(true) { String line = reader.readLine(); if(line == null) break; System.out.println(line); } } catch(FileNotFoundException e){ System.out.println("文件未找到:" + e.getMessage()); } catch(IOException e){ System.out.println("读取失败:" + e.getMessage()); } finally{ System.out.println("已关闭文件流"); reader.close(); fis.close(); }
转载地址:http://zvryk.baihongyu.com/