编程语言
首页 > 编程语言> > Java从文件读取数据

Java从文件读取数据

作者:互联网

从user.txt把所有数据都读出来装到map中输出:

public static Map<String, String> getMap(){
        Map<String, String> map = new HashMap<>();

        try {
            String encoding="GBK";
            File file=new File("./web/user.txt");
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while((lineTxt = bufferedReader.readLine()) != null){
                    String[] s = lineTxt.split(" ");
                    map.put(s[0],s[1]);
                }
                read.close();
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return map;
    }
 public static void main(String[] args) {
        Map<String, String> map = User.getMap();
        for(Map.Entry<String,String> m : map.entrySet()){
            System.out.println("m.getKey() = " + m.getKey());
            System.out.println("m.getValue() = " + m.getValue());
        }


    }

 

 

标签:map,Java,读取数据,Map,System,从文件,file,new,out
来源: https://www.cnblogs.com/wyw123456/p/15619588.html