//将str1替换为str1
    //FilePath为文件路径
    public void changeTxtContent(String FilePath,String str1,String str2) throws Exception{
        File file = new File(FilePath);
        String code = getFileCharacterEnding(file);//获取文件编码
        InputStreamReader read = new InputStreamReader(new FileInputStream(
            file), code);
        BufferedReader bufferedReader = new BufferedReader(read);
        String TxtBuff=null;
        String out="";
        while((TxtBuff = bufferedReader.readLine()) !=null){
            TxtBuff = TxtBuff.replace(str1, str2);
            out+= TxtBuff;
        }
        read.close();
        FileOutputStream outputstream=null; 
        outputstream = new FileOutputStream(file);
        outputstream.write(out.getBytes(code));  
        outputstream.close(); 
    }

获取文件编码

public static String getFileCharacterEnding(File file) throws Exception {
        InputStream inputStream = new FileInputStream(file); 
        byte[] head = new byte[3];  
        inputStream.read(head);   
        String code = "gbk";
        if (head[0] == -1 && head[1] == -2){
            code = "UTF-16";
        }
        if (head[0] == -2 && head[1] == -1){
            code = "Unicode";
        }
        if (head[0] == -17 && head[1] == -69 && head[2] == -65){
            code = "UTF-8";
        } 
       try{ inputStream.close();}catch (Exception e) {}
        System.out.println(code); 
        
        return code;
    }

 

这种方法应该不适合跨行内容的替换,如果要换行内容要替换的话 ,可以试下 out=out.replace(str1, str2);