轉化文本文件爲UTF8無BOM

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ToUtf8NoBOM {

	/**
	 * 入口函數
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		if (args.length < 2) return;
		else {
			String strSuffix = args[0];
			String strFile = null;
			for (int i = 1; i < args.length; i++) {
				strFile = args[i];
				winToLinux(strFile, strSuffix);
			}
		}
	}

	/**
	 * 將文件轉換爲UTF8無BOM,若參數爲文件件,則轉換全部指定後綴的文件爲UTF8無BOM
	 * 
	 * @param strFile 文件或文件夾
	 * @param strSuffix 後綴
	 * @throws Exception 異常
	 */
	private static void winToLinux(String strFile, String strSuffix)
			throws Exception {
		File file = new File(strFile);
		if (file.isFile()) {
			if (strFile.endsWith(strSuffix)) {
				convertToUtf8NoBOM(file);
			} else {
				return;
			}
		} else {
			for (String str : file.list()) {
				winToLinux(file.getPath() + File.separatorChar + str, strSuffix);
			}
		}
	}

	/**
	 * 將文件轉化爲UTF8無BOM
	 * 
	 * @param file
	 * @throws IOException
	 */
	private static void convertToUtf8NoBOM(File file) throws IOException {
		String strText = null;

		// 讀取文件
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			byte[] buf = new byte[(int) file.length()];
			in.read(buf);
			if (buf.length > 3 && (byte) 0XEF == buf[0] && (byte) 0XBB == buf[1] && (byte) 0XBF == buf[2]) {
				strText = new String(buf, 3, buf.length - 3, "UTF-8");
			} else {
				strText = new String(buf);
			}
			strText.replace("\r\n", "\n");
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (null != in) {
				in.close();
			}
		}

		// 寫文件
		OutputStream out = null;
		try {
			out = new FileOutputStream(file);
			out.write(strText.getBytes("UTF-8"));
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (null != out) {
				out.flush();
				out.close();
			}
		}
	}
}

說明:java

一、編譯生成字節碼文件ToUtf8NoBOM.class函數

在命令行運行以下命令便可命令行

javac ToUtf8NoBOM.javacode

二、使用舉例get

(1)多文件批量轉換it

在命令行運行以下命令io

java ToUtf8NoBOM .java D:\myjava\src編譯

可將D:\myjava\src下全部後綴名爲「.java」的文本文件轉化爲UTF8無BOM格式class

(2)單個文件轉換
test

在命令行運行以下命令

java ToUtf8NoBOM .java D:\myjava\src\test.java

可將文件「D:\myjava\src\test.java」轉化爲UTF8無BOM格式

相關文章
相關標籤/搜索