1. 程式人生 > >讀取檔案的工具類

讀取檔案的工具類

讀取檔案的工具類:

public class FileUtil {

    public String readToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in
= new FileInputStream(file); in.read(filecontent); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { return new String(filecontent, encoding); } catch
(UnsupportedEncodingException e) { System.err.println("The OS does not support " + encoding); e.printStackTrace(); return null; } } }

這裡寫圖片描述

讀取test.properties檔案,路徑是: D:\springtest\src\main\resources\test.properties

        FileUtil fileUtil = new FileUtil();
        String result = fileUtil.readToString("D:\\
springtest\\src\\main\\resources\\test.properties"); System.out.println("result is :"+result);