问题描述
大作业的题目是网络聊天室。我序列化一个HashMap来传递数据。我看这部分的代码一般都是 SocketChannel sc = (SocketChannel) key.channel(); int number = sc.read(buffer);上面的buffer一般是固定大小的比如 8096等等。可是如果对象较大 超过了 buffer大小怎么办呢?? 问题补充:<div class="quote_title">alvin198761 写道</div><div class="quote_div"><pre name="code" class="java">/** * java NIO operate * * @author 唐植超 * */public class FileUtil {。 。 。}</pre>我没写注释,但是你肯定看的懂,</div><br /><br />我指的是在客户端接收服务器端传来的数据。<br />你这个解决不了我的问题吧?<br />
解决方案
data = ByteBuffer.allocate((int) fc.size()); fc.read(data); fc.close();
解决方案二:
建议你用对象反序列化,将二进制转成对象
解决方案三:
package io.util.alvin.file;import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;/** * java NIO operate * * @author 唐植超 * */public class FileUtil {private FileUtil() {}public static String readToStr(String path) throws IOException {return new String(readToByte(path));}public static byte[] readToByte(String path) throws IOException {return readToByte(new File(path));}public static byte[] readToByte(File f) throws IOException {RandomAccessFile raf = null;FileChannel fc = null;ByteBuffer data = null;raf = new RandomAccessFile(f, "r");fc = raf.getChannel();data = ByteBuffer.allocate((int) fc.size());fc.read(data);fc.close();return null;}public static void writeFile(String path, byte[] data) throws IOException {writeFile(new File(path), data);}public static void writeFile(File f, byte[] data) throws IOException {RandomAccessFile raf = null;ByteBuffer dts = null;FileChannel fc = null;raf = new RandomAccessFile(f, "w");fc = raf.getChannel();dts = ByteBuffer.wrap(data);fc.write(dts);fc.close();}public static void copyFile(File srcFile, File targetFile)throws IOException {RandomAccessFile sourceFile = null;RandomAccessFile pasteFile = null;FileChannel srcChannel = null;FileChannel targetChannel = null;sourceFile = new RandomAccessFile(srcFile, "r");pasteFile = new RandomAccessFile(targetFile, "rw");srcChannel = sourceFile.getChannel();targetChannel = pasteFile.getChannel();targetChannel.transferFrom(srcChannel, 0, srcChannel.size());srcChannel.close();targetChannel.close();}public static void copyFile(String srcPath, String targetPath)throws IOException {copyFile(new File(srcPath), new File(targetPath));}public static void deleteFile(File f) {deleteFile(f.getAbsolutePath());}public static void deleteFile(String path) {File f = new File(path);if (!f.exists()) {return;}if (f.isFile()) {f.delete();return;}String[] children;children = f.list();if (children == null) {return;}if (children.length == 0) {return;}for (String s : children) {deleteFile(path.concat(File.separator).concat(s));}}public static void moveFile(String oldPath, String newPath)throws IOException {copyFile(oldPath, newPath);deleteFile(oldPath);}}我没写注释,但是你肯定看的懂,
解决方案四:
同问~~求牛人解答~~~~~~