Java reads the contents of a txt file and assigns it to String

private String readFileToString(File file) {
    
    
		BufferedReader bfr = null;
		StringBuffer sb = new StringBuffer();
		try {
    
    
			bfr = new BufferedReader(new FileReader(file));
			String line = null;
			while ((line = bfr.readLine()) != null) {
    
    
				sb.append(line);
			}
			return sb.toString();
		} catch (FileNotFoundException e) {
    
    
			e.printStackTrace();
		} catch (IOException e) {
    
    
			e.printStackTrace();
		} finally {
    
    
			if (bfr != null) {
    
    
				try {
    
    
					bfr.close();
				} catch (IOException e) {
    
    
					e.printStackTrace();
				}
			}
		}
		return null;
}
import java.io.bufferedreader;
import java.io.filereader;

public class myfilereader {
    
    

    public static void main(string[] args)throws exception{
    
    
        //文件绝对路径改成你自己的文件路径
        filereader fr=new filereader("d:\\workspace\\mylearn\\count.txt");
        //可以换成工程目录下的其他文本文件
        bufferedreader br=new bufferedreader(fr);
        while(br.readline()!=null){
    
    
            string s=br.readline();
            system.out.println(s);
        }
        br.close();
    }

}

Guess you like

Origin blog.csdn.net/qq_49641620/article/details/130082511