Java读取text文件

代码如下:

package com.work.javaio;

import java.io.*;

public class ReadTxt {
    public static void readTxtFile(String filePath){
        try{
            String encoding = "UTF-8";
            File file = new File(filePath);
            if(file.isFile() && file.exists()){
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader read = new InputStreamReader(fileInputStream,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 (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String filePath = "D:\\temp\\hello.txt";
        readTxtFile(filePath);
    }
}

 

posted @ 2020-11-30 10:13  alittlecomputer  阅读(662)  评论(0)    收藏  举报