如何把对象和一般数据写入同一个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
byte[] buff = new byte[hexString.length() / 2];
int buffIndex = 0;
byte nowByte = 0;
for (int count = 0; count < hexString.length(); count += 2) {
h = (byte) (((byte) checkCharIndex(hexString.charAt(count))) << 4);
l = (byte) checkCharIndex(hexString.charAt(count + 1));
nowByte = (byte) (nowByte
[解决办法]
h);
nowByte = (byte) (nowByte
[解决办法]
l);
buff[buffIndex++] = nowByte;
nowByte = 0;
}
return buff;
}
/**
* find hex table index.
* return 0 if not found.
* @param c need find char.
* @return less than 0 means not found.
*/
private static int checkCharIndex(char c) {
int index = -1;
for (int count = 0; count < hexChars.length; count++) {
if (c == hexChars[count]) {
index = count;
break;
}
}
return index;
}
}