日期:2014-05-20  浏览次数:20755 次

如何把对象和一般数据写入同一个txt文件
我想把一些对象写入txt文件,我知道可以使用序列化的办法把对象写入文件,但是序列化的方法用的是ObjectOutputStream,而普通的数据写入文件用的是FileOutputStream,这两种数据写入方法可以混用吗?如何混用?读取的时候如何分清楚哪些是普通数据那些是对象?

------解决方案--------------------
不管你用的是ObjectOutputStream还是FileOutputStream都是OutputStream只是实现不同而已....建议再回炉看一下IO这节吧.

你说的场景当然可以,把对象序列化后其实就是一堆字节码了,那么你的问题就是如何把一堆字节码写入txt文本文件了.

public static byte[] objectToByte(Object obj) throws IOException {
        ByteArrayOutputStream buff = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(buff);
        out.writeObject(obj);
        try {
            return buff.toByteArray();
        } finally {
            out.close();
        }
 }

public static Object byteToObject(byte[] b)
            throws IOException, ClassNotFoundException {
        ByteArrayInputStream buff = new ByteArrayInputStream(b);
        ObjectInputStream in = new ObjectInputStream(buff);
        Object obj = in.readObject();
        try {
            return obj;
        } finally {
            in.close();
        }
    }

我提供一个这样的方法,对象经过这个方法就得到了你要的对象序列化后的字节数组了.

然就是就是把字节码转换成字符串,以方便写入文本文件.
这里我提供一个工具类,这是我自己写用以平时项目中使用的一个将字节码可视化的.


public class PrivacyUtil {

    /**
     * hex table
     */
    private static char[] hexChars = {
        '0', '1', '2', '3', '4', '5', '6', '7',
        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };

    /**
     * do not allow instantiation.
     */
    private PrivacyUtil() {
    }

    /**
     * bytes to string.
     * @param b src bytes。
     * @return hex string。
     */
    public static String toHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            sb.append(hexChars[(b[i] & 0xf0) >>> 4]);
            sb.append(hexChars[b[i] & 0x0f]);
        }
        return sb.toString();
    }

    /**
     * hex string to bytes
     * @param hexString hex string.
     * @return src bytes.
     */
    public static byte[] toOriginalByte(String hexString) {
        if (hexString == null 
------解决方案--------------------
 hexString.isEmpty()) {
            return null;
        }
        byte h;//hight index
        byte l;//low index