5/28/2010

Ghi tập tin unicode trong Java [new]

Cách này (có lẽ) đơn giản hơn cách trước. Nhưng trong đoạn code này, chỉ khai một một ByteBuffer có 1024 bytes, khi ghi một chuỗi quá dài sẽ quăng lỗi java.nio.BufferOverflowException

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
*
* @author hungnq
*/
public class UnicodeUtil {

/**
* Constructor of class UnicodeUtil
*/
public UnicodeUtil(){

}
/**
*
* @param contents
* @param filePath
*/
public static void writeUnicode(String contents,String filePath){
try {
//Get byte of String in UFT-8 charset
byte[] utf8byte = contents.getBytes("UTF-8");
File aFile = new File(filePath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(aFile, true);
System.out.println("FileStream created successfully!");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
FileChannel fc = fos.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
for (byte b : utf8byte) {
buf.put(b);
}
buf.flip();
try {
fc.write(buf);
fc.close();
System.out.println("Buffered contents written to file.");
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
}
}
Sử dụng như sau
String phrase = new String("Công bố phần mềm kế toán online đầu tiên tại Việt Nam");
String filePath = "C:"+File.separator+"unicode.txt";
UnicodeUtil.writeUnicode(phrase,filePath);

No comments:

Post a Comment

The 0/1 Knapsack Problem - Dynamic Programming

 References: https://www.youtube.com/watch?v=EH6h7WA7sDw  Class Item class Item { private $_weight; private $_value; public functi...