java读取txt文件内容。可以作如下理解:
- package com.campu;
- import java.io.BufferedInputStream;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.InputStreamReader;
- import java.io.Reader;
- /**
- * @author Java团长
- * H20121012.java Java学习交流QQ群:589809992 我们一起学Java!
- * 2017-09-26下午18:52
- */
- public class H20121012 {
- /**
- * 功能:Java读取txt文件的内容
- * 步骤:1:先获得文件句柄
- * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
- * 3:读取到输入流后,需要读取生成字节流
- * 4:一行一行的输出。readline()。
- * 备注:需要考虑的是异常情况
- * @param filePath
- */
- public static void readTxtFile(String filePath) {
- try {
- String encoding = "GBK";
- File file = new File(filePath);
- if (file.isFile() && file.exists()) { //判断文件是否存在
- InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding); //考虑到编码格式
- BufferedReader bufferedReader = new BufferedReader(read);
- String lineTxt = null;
- while ((lineTxt = bufferedReader.readLine()) != null) {
- System.out.println(lineTxt);
- }
- read.close();
- } else {
- System.out.println("找不到指定的文件");
- }
- } catch(Exception e) {
- System.out.println("读取文件内容出错");
- e.printStackTrace();
- }
- }
- public static void main(String argv[]) {
- String filePath = "L:\\Apache\\htdocs\\res\\20121012.txt";
- // "res/";
- readTxtFile(filePath);
- }
- }
我有一个微信公众号,经常会分享一些Java技术相关的干货。如果你喜欢我的分享,可以用微信搜索“Java团长”或者“javatuanzhang”关注。
来源: https://cloud.tencent.com/developer/article/1006811