题目描述:
限定使用socket通信来完成。需要实现的功能是:客户端读取10G的文本
文件以"换行啦啦啦"作为换行符、将文件中的内容、按行发送给服务端。服务端接收数据后、将文本文件保存在服务端所在电脑的磁盘上。合理使用线程!!
public static void main(String[] args) throws IOException {
//监听端口
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//切换非阻塞
serverSocketChannel.configureBlocking(false);
//绑定端口
serverSocketChannel.bind(new InetSocketAddress("localhost",9696));
//注册选择器
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
FileChannel outChannel = FileChannel.open(Paths.get("你的文件"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
while (selector.select() > 0){
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while(iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
if(selectionKey.isAcceptable()){
SocketChannel client = serverSocketChannel.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}else if(selectionKey.isReadable()){
SocketChannel client = (SocketChannel) selectionKey.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (client.read(buffer) > 0){
buffer.flip();
//byte[] bytes = new byte[buffer.limit()];
//buffer.get(bytes);
outChannel.write(buffer);
}
}
iterator.remove();
}
}
}
换行符自个替换
这样替换换行符就可以了
public static byte[] replaceNewline(byte[] b) throws IOException{
byte[] line = "换行啦啦啦".getBytes();
ByteArrayOutputStream os = new ByteArrayOutputStream();
for(int i=0;i<b.length;i++) {
if(b[i]==10) {
os.write(line);
}else {
os.write(b[i]);
}
}
return os.toByteArray();
}
首先,10G大文件的发送,需要考虑多线程。
其次,大文件需要考虑切分成多个完整的块文件,然后服务器端存储的时候可以存多个文件。
GitChat 上介绍 Java 多线程解析大文件的文章:https://gitbook.cn/gitchat/activity/5cac60e33bc6823cd6c9900f
有需要可以参考看看。