Java file文件读写操作

file 写入文件:

 /**
     * //写入文件
     * @param fileName �ļ�����
     * @param data json�ַ���
     */
    public void saveDataToFile(String groupid,String user){
        BufferedWriter writer = null;
     
        String data=null;
        File file = new File( AgentGlobals.getXMLProperty("groupinfo",
                "C:\\Program Files (x86)\\eastcom\\config\\groupinfo.xml"));
        Log.info(file+"file");
        //判断文件是否存在
        if(!file.exists()){
            Log.info("***********");
            try {
          //文件不存在,创建文件 file.createNewFile(); data
="<?xml version=\"1.0\" encoding=\"utf-8\"?><groupinfo><"+groupid+">"+user+"</"+groupid+"></groupinfo>"; } catch (IOException e) { e.printStackTrace(); } }else{
        //当文件存在时,读取原文件的内容 String getfiles
= getfile(); Log.info("getfiles"+getfiles); if("".equals(getfiles)){ data="<?xml version=\"1.0\" encoding=\"utf-8\"?><groupinfo><"+groupid+">"+user+"</"+groupid+"></groupinfo>"; }else{ data=getfiles.substring(0, getfiles.lastIndexOf("</groupinfo>"))+"<"+groupid+">"+user+"</"+groupid+"></groupinfo>"; } } //� try { Log.info(data);
        // false:清空原文件的内容,在写入文件 true:直接在原文件里面接着添加内容 writer
= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false), "UTF-8")); writer.write(data); } catch (IOException e) { e.printStackTrace(); }finally { try { if(writer != null){ writer.close(); } } catch (IOException e) { e.printStackTrace(); } } Log.info("写入文件完成"); }

file读取文件:

/**
     * //��ȡ����
     * @param fileName读取文件
     */
    public String getfile() {
        File file = new File( AgentGlobals.getXMLProperty("groupinfo",
                "C:\\Program Files (x86)\\eastcom\\config\\groupinfo.txt"));
        if(!file.exists()){
          
            return null;
        }
        BufferedReader reader = null;
        String laststr = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null){
                laststr += tempString;
            }
            reader.close();
            
            Log.info("laststr"+laststr);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Log.info("读取文件结束");
        return laststr;
    }
posted @ 2020-01-17 10:09  哎呀呀呀呀~~  阅读(640)  评论(0编辑  收藏  举报