参考工具  http://akini.mbnet.fi/java/unicodereader/

Utf8BomRemover 清除bom的方法
  1. package cn.com.do1.component.common.util;
  2. import java.io.*;
  3. import java.nio.charset.Charset;
  4. public class Utf8BomRemover {
  5. /**
  6. * 读取流中前面的字符,看是否有bom,如果有bom,将bom头先读掉丢弃
  7. *
  8. * @param in
  9. * @return
  10. * @throws java.io.IOException
  11. */
  12. public static InputStream getInputStream(InputStream in) throws IOException {
  13. PushbackInputStream testin = new PushbackInputStream(in);
  14. int ch = testin.read();
  15. if (ch != 0xEF) {
  16. testin.unread(ch);
  17. } else if ((ch = testin.read()) != 0xBB) {
  18. testin.unread(ch);
  19. testin.unread(0xef);
  20. } else if ((ch = testin.read()) != 0xBF) {
  21. throw new IOException("错误的UTF-8格式文件");
  22. } else {
  23. // 不需要做,这里是bom头被读完了
  24. // // System.out.println("still exist bom");
  25. }
  26. return testin;
  27. }
  28. /**
  29. * 根据一个文件名,读取完文件,干掉bom头。
  30. *
  31. * @param fileName
  32. * @throws java.io.IOException
  33. */
  34. public static void trimBom(String fileName) throws IOException {
  35. FileInputStream fin = new FileInputStream(fileName);
  36. // 开始写临时文件
  37. InputStream in = getInputStream(fin);
  38. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  39. byte b[] = new byte[4096];
  40. int len = 0;
  41. while (in.available() > 0) {
  42. len = in.read(b, 0, 4096);
  43. // out.write(b, 0, len);
  44. bos.write(b, 0, len);
  45. }
  46. in.close();
  47. fin.close();
  48. bos.close();
  49. // 临时文件写完,开始将临时文件写回本文件。
  50. System.out.println("[" + fileName + "]");
  51. FileOutputStream out = new FileOutputStream(fileName);
  52. out.write(bos.toByteArray());
  53. out.close();
  54. System.out.println("处理文件" + fileName);
  55. }
  56. public static void main(String[] args) throws IOException {
  57. //刪除指定文件夾下(含子文件夾)所有java文件的BOM,若構造器中參數為null則刪除所有文件頭部BOM
  58. new Utf8BomRemover( "java" ).start( "\"F:\\\\flwork\\\\gmmsDGYH\\\\src\\\\com");
  59. }
  60. /**
  61. * 根据一个文件名,读取完文件,干掉bom头2 这里使用了第三方类UnicodeReader
  62. *
  63. * @throws java.io.IOException
  64. */
  65. public void saveFile(String file) throws IOException {
  66. InputStream in= new FileInputStream( file);
  67. BufferedReader bre = null;
  68. OutputStreamWriter pw = null;//定义一个流
  69. CharArrayWriter writer = new CharArrayWriter();
  70. //这一句会读取BOM头
  71. //bre = new BufferedReader(new InputStreamReader(in, "UTF-8"));
  72. //这一句会干掉BOM头
  73. bre = new BufferedReader(new UnicodeReader(in, Charset.defaultCharset().name()));//
  74. String line = bre.readLine();
  75. while(line != null)
  76. {
  77. writer.write(line);
  78. /*
  79. 加上这段代码可以查看更详细的16进制
  80. byte[] allbytes = line.getBytes("UTF-8");
  81. for (int i=0; i < allbytes.length; i++)
  82. {
  83. int tmp = allbytes[i];
  84. String hexString = Integer.toHexString(tmp);
  85. // 1个byte变成16进制的,只需要2位就可以表示了,取后面两位,去掉前面的符号填充
  86. hexString = hexString.substring(hexString.length() -2);
  87. System.out.print(hexString.toUpperCase());
  88. System.out.print(" ");
  89. }*/
  90. line = bre.readLine();
  91. }
  92. writer.flush();
  93. bre.close();
  94. FileWriter f2 = new FileWriter(file);
  95. writer.writeTo(f2);
  96. f2.close();
  97. writer.close();
  98. }
  99. private String extension = null ;
  100. public Utf8BomRemover(String extension) {
  101. super ();
  102. this .extension = extension;
  103. }
  104. /** 啟動對某個文件夾的篩選 */
  105. @SuppressWarnings ( "unchecked" )
  106. public void start(String rootDir) throws IOException {
  107. traverseFolder2(rootDir);
  108. }
  109. public void traverseFolder2(String path) throws IOException {
  110. File file = new File(path);
  111. if (file.exists()) {
  112. File[] files = file.listFiles();
  113. if (files.length == 0) {
  114. System.out.println("文件夹是空的!");
  115. return;
  116. } else {
  117. for (File file2 : files) {
  118. if (file2.isDirectory()) {
  119. System.out.println("文件夹:" + file2.getAbsolutePath());
  120. traverseFolder2(file2.getAbsolutePath());
  121. } else {
  122. remove(file2.getAbsolutePath());
  123. }
  124. }
  125. }
  126. } else {
  127. System.out.println("文件不存在!");
  128. }
  129. }
  130. /** 移除UTF-8的BOM */
  131. private void remove(String path) throws IOException {
  132. saveFile(path);
  133. trimBom(path);
  134. }
  135. }

第二种方法的UnicodeReader 类


  1. package cn.com.do1.component.common.util;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.PushbackInputStream;
  6. import java.io.Reader;
  7. /**
  8. version: 1.1 / 2007-01-25
  9. - changed BOM recognition ordering (longer boms first)
  10. 网络地址:http://koti.mbnet.fi/akini/java/unicodereader/UnicodeReader.java.txt
  11. Original pseudocode : Thomas Weidenfeller
  12. Implementation tweaked: Aki Nieminen
  13. http://www.unicode.org/unicode/faq/utf_bom.html
  14. BOMs:
  15. 00 00 FE FF = UTF-32, big-endian
  16. FF FE 00 00 = UTF-32, little-endian
  17. EF BB BF = UTF-8,
  18. FE FF = UTF-16, big-endian
  19. FF FE = UTF-16, little-endian
  20. Win2k Notepad:
  21. Unicode format = UTF-16LE
  22. ***/
  23. /**
  24. * Generic unicode textreader, which will use BOM mark
  25. * to identify the encoding to be used. If BOM is not found
  26. * then use a given default or system encoding.
  27. */
  28. public class UnicodeReader extends Reader {
  29. PushbackInputStream internalIn;
  30. InputStreamReader internalIn2 = null;
  31. String defaultEnc;
  32. private static final int BOM_SIZE = 4;
  33. /**
  34. *
  35. * @param in inputstream to be read
  36. * @param defaultEnc default encoding if stream does not have
  37. * BOM marker. Give NULL to use system-level default.
  38. */
  39. UnicodeReader(InputStream in, String defaultEnc) {
  40. internalIn = new PushbackInputStream(in, BOM_SIZE);
  41. this.defaultEnc = defaultEnc;
  42. }
  43. public String getDefaultEncoding() {
  44. return defaultEnc;
  45. }
  46. /**
  47. * Get stream encoding or NULL if stream is uninitialized.
  48. * Call init() or read() method to initialize it.
  49. */
  50. public String getEncoding() {
  51. if (internalIn2 == null) return null;
  52. return internalIn2.getEncoding();
  53. }
  54. /**
  55. * Read-ahead four bytes and check for BOM marks. Extra bytes are
  56. * unread back to the stream, only BOM bytes are skipped.
  57. */
  58. protected void init() throws IOException {
  59. if (internalIn2 != null) return;
  60. String encoding;
  61. byte bom[] = new byte[BOM_SIZE];
  62. int n, unread;
  63. n = internalIn.read(bom, 0, bom.length);
  64. if ( (bom[0] == (byte)0x00) && (bom[1] == (byte)0x00) &&
  65. (bom[2] == (byte)0xFE) && (bom[3] == (byte)0xFF) ) {
  66. encoding = "UTF-32BE";
  67. unread = n - 4;
  68. } else if ( (bom[0] == (byte)0xFF) && (bom[1] == (byte)0xFE) &&
  69. (bom[2] == (byte)0x00) && (bom[3] == (byte)0x00) ) {
  70. encoding = "UTF-32LE";
  71. unread = n - 4;
  72. } else if ( (bom[0] == (byte)0xEF) && (bom[1] == (byte)0xBB) &&
  73. (bom[2] == (byte)0xBF) ) {
  74. encoding = "UTF-8";
  75. unread = n - 3;
  76. } else if ( (bom[0] == (byte)0xFE) && (bom[1] == (byte)0xFF) ) {
  77. encoding = "UTF-16BE";
  78. unread = n - 2;
  79. } else if ( (bom[0] == (byte)0xFF) && (bom[1] == (byte)0xFE) ) {
  80. encoding = "UTF-16LE";
  81. unread = n - 2;
  82. } else {
  83. // Unicode BOM mark not found, unread all bytes
  84. encoding = defaultEnc;
  85. unread = n;
  86. }
  87. //System.out.println("read=" + n + ", unread=" + unread);
  88. if (unread > 0) internalIn.unread(bom, (n - unread), unread);
  89. // Use given encoding
  90. if (encoding == null) {
  91. internalIn2 = new InputStreamReader(internalIn);
  92. } else {
  93. internalIn2 = new InputStreamReader(internalIn, encoding);
  94. }
  95. }
  96. public void close() throws IOException {
  97. init();
  98. internalIn2.close();
  99. }
  100. public int read(char[] cbuf, int off, int len) throws IOException {
  101. init();
  102. return internalIn2.read(cbuf, off, len);
  103. }
  104. }




java 清除 bom的更多相关文章

  1. Linux下查找包含BOM头的文件和清除BOM头命令 2014-08-16 12:30:50

    Linux下查找包含BOM头的文件和清除BOM头命令 2014-08-16 12:30:50 分类: 系统运维 查找包含BOM头的文件,命令如下: 点击(此处)折叠或打开 grep -r -I -l ...

  2. 批量清除BOM头

    批量清除BOM头 (2012-03-05 13:28:30) 转载▼ 标签: 杂谈   有些php文件由于不小心保存成了含bom头的格式而导致出现一系列的问题.以下是批量清除bom头的代码,复制代码, ...

  3. Java清除:收尾和垃圾收集

    垃圾收收集器(GC)只知道释放由new关键字分配的内存,所以不知道如何释放对象的"特殊"内存.为了解决这个问题,Java提供了一个名为:finalize()的方法,可为我们的类定义 ...

  4. 2018-03-21 11:34:44 java脚本批量转换java utf-8 bom源码文件为utf-8编码文件

    package com.springbootdubbo; import java.io.*;import java.util.ArrayList;import java.util.List; /** ...

  5. java清除所有微博短链接 Java问题通用解决代码

    java实现微博短链接清除,利用正则,目前只支持微博短链接格式为"http://域名/字母或数字8位以内"的链接格式,现在基本通用 如果链接有多个,返回结果中会有多出的空格,请注意 ...

  6. linux下查找包含BOM头的文件和清除BOM头命令

    查找包含BOM头的文件,命令如下:   grep -r -I -l $'^\xEF\xBB\xBF' ./   这条命令会查找当前目录及子目录下所有包含BOM头的文件,并把文件名在屏幕上输出.   但 ...

  7. 清除BOM头源码

    BOM: Byte Order Mark UTF-8 BOM又叫UTF-8 签名,其实UTF-8 的BOM对UFT-8没有作用,是为了支援UTF-16,UTF-32才加上的BOM,BOM签名的意思就是 ...

  8. Linux 查找bom头文件,清除bom头命令

    1.查找bom头文件 grep -r -I -l $'^\xEF\xBB\xBF' ./ 2.替换bom头文件 find . -type f -exec sed -i 's/\xEF\xBB\xBF/ ...

  9. JAVA输出带BOM的UTF-8编码的文件

    当从http 的response输出CSV文件的时候,设置为utf8的时候默认是不带bom的,可是windows的Excel是使用bom来确认utf8编码的,全部须要把bom写到文件的开头. 微软在 ...

随机推荐

  1. OpenCV学习(10) 图像的腐蚀与膨胀(1)

    建议大家看看网络视频教程:http://www.opencvchina.com/thread-886-1-1.html    腐蚀与膨胀都是针对灰度图的形态学操作,比如下面的一副16*16的灰度图. ...

  2. C#常见算法题目

        //冒泡排序    public class bubblesorter    {        public void sort(int[] list)        {            ...

  3. J2EE 中 用 El表达式 和 Jsp 方式 取得 URL 中的参数方法

    使用 el表达式方法: var urlParamValue = "${param.urlVarName}"; 使用 Jsp 表达式 var urlParamValue2 = &qu ...

  4. [Node.js] Level 6. Socket.io

    6.2 Setting Up socket.io Server-Side So far we've created an Express server. Now we want to start bu ...

  5. 委托批量处理Excel

    在以前的博文中--CAD批量处理工具--BatchProc,即只要用户输入处理单个文件的代码,即可批量处理多个文件.使用起来特别方便. 在现在的地籍处理中,处理Excel的情况比较多,尤其需要反反复复 ...

  6. Java中解压文件名有中文的rar包出现乱码问题的解决

    import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import j ...

  7. 算法笔记_009:字符串匹配(Java)

    1 问题描述 给定一个n个字符组成的串(称为文本),一个m(m <= n)的串(称为模式),从文本中寻找匹配模式的子串. 2 解决方案 2.1 蛮力法 package com.liuzhen.c ...

  8. Android 再按一次退出应用的代码

    private long exitTime = 0; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (key ...

  9. vue vm.$attrs 使用

    1.vm.$attrs 说明 https://cn.vuejs.org/v2/api/#vm-attrs 将父组件的属性(除去在props中传入的属性)传递给子组件. 2.代码分析 以下是elemen ...

  10. Warning: cast to/from pointer from/to integer of different size

    将int变量转为(void*)时出现错误 error: cast to pointer from integer of different size [-Werror=int-to-pointer-c ...