java读取文件内容到字符串

方法一:使用BuffererReader.继承Reader类

public void fileRead() throws Exception {
        File file = new File("D:\\test.txt");//定义一个file对象,用来初始化FileReader
        FileReader reader = new FileReader(file);//定义一个fileReader对象,用来初始化BufferedReader
        BufferedReader bReader = new BufferedReader(reader);//new一个BufferedReader对象,将文件内容读取到缓存
        StringBuilder sb = new StringBuilder();//定义一个字符串缓存,将字符串存放缓存中
        String s = "";
        while ((s =bReader.readLine()) != null) {//逐行读取文件内容,不读取换行符和末尾的空格
            sb.append(s + "\n");//将读取的字符串添加换行符后累加存放在缓存中
            System.out.println(s);
        }
        bReader.close();
        String str = sb.toString();
        System.out.println(str );
    }

方法二: 使用FileInputStream类

private static String getTemplateContent() throws Exception{
    File file = new File("D:\\test.txt");
    if(!file.exists()){
        return null;
    }
    FileInputStream inputStream = new FileInputStream(file);
    int length = inputStream.available();
    byte bytes[] = new byte[length];
    inputStream.read(bytes);
    inputStream.close();
    String str =new String(bytes, StandardCharsets.UTF_8);
    return str ;
}

你可能感兴趣的:(csdn,java)