Java读取txt文件中的数据赋给String变量方法

时间:2022-10-28 11:58:19

实例如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class MainActivity {
    
    private static final String fileName = "D:/Tao/MyEclipseWorkspace/resources/weather.txt";
    
    public static void main(String[] args) {
        
        //读取文件
        BufferedReader br = null;
        StringBuffer sb = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"GBK")); //这里可以控制编码
            sb = new StringBuffer();
            String line = null;
            while((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }  
        }
        
        String data = new String(sb); //StringBuffer ==> String
        System.out.println("数据为==> " + data);
            
    }
    
}

以上这篇Java读取txt文件中的数据赋给String变量方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/hbtj_1216/article/details/52036885