Restlet流式读取远端文件内容 InputRepresentation
OneCoder 验证用Restlet做服务,读取远端文件内容功能,编写验证代码。目前测试通过,主要是利用restlet内部提供的InputRepresentation对象,通过ReadableByteChannel,按字节流的方式读取文件内容。代码如下,省略注册服务的...
OneCoder验证用Restlet做服务,读取远端文件内容功能,编写验证代码。目前测试通过,主要是利用restlet内部提供的InputRepresentation对象,通过ReadableByteChannel,按字节流的方式读取文件内容。代码如下,省略注册服务的部分,只给出服务端和客户端关键代码:
服务端:
package com.coderli.restlet.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.restlet.representation.InputRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
/**
* 文件读取服务端
*
* @author lihzh(OneCoder)
* @date 2013年12月4日 下午4:35:22
* @website http://www.coderli.com
*/
public class MacFile extends ServerResource {
@Get
public InputRepresentation readFile() throws FileNotFoundException {
System. out.println("开始读取文件" );
File file = new File("/Users/apple/Documents/stockdata/SH600177.TXT" );
InputStream inputStream = new FileInputStream(file);
InputRepresentation inputRepresentation = new InputRepresentation(
inputStream);
return inputRepresentation;
}
}客户端:
package com.coderli.restlet.file;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import org.restlet.data.MediaType;
import org.restlet.representation.ReadableRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
/**
* 文件读取,客户端
*
* @author lihzh(OneCoder)
* @date 2013年12月4日 下午4:36:00
*/
public class MacFileClient {
public static void main(String[] args) throws IOException {
ClientResource clientResource = new ClientResource(
"http://localhost:8182/macFile" );
Representation rp = clientResource.get(MediaType.ALL );
ReadableRepresentation rRepresentation = (ReadableRepresentation) rp;
ReadableByteChannel rbc = rRepresentation.getChannel();
ByteBuffer bb = ByteBuffer. allocate(1024);
int index = -1;
do {
index = rbc.read(bb);
if (index <= 0) {
break;
}
bb.position(0);
byte[] bytes = new byte[index];
bb.get(bytes);
System. out.print(new String(bytes, "gbk"));
bb.clear();
} while (index > 0);
}
}需要注意的是,这里客户端实现中的System.out.print部分是由缺陷的,在有汉字的时候,会因为不正确的截断字节数组造成乱码。这里是因为我验证的时候文件只有英文和数组,所以简单的采用此种方式。
看完题解,马上用 240 关实战检验掌握度
覆盖 GESP 1~8 级考纲心法、CSP-J 双栏阅读程序、错题动态变式推演与 90/120 分钟全真模考。
配套题解代码归档于 yummy-code 仓库,完整知识点索引见 GESP Wiki。
同专栏相关推荐
Restlet 2.1.4中 匪夷所思的ObjectRepresentation的构造函数
OneCoder 使用Restlet最新版2.1.4开发样例,却一直抛出异常: Exception in thread "main" java.lang.IllegalArgumentException : The serialized representation m...
Restlet2.1.6发布,修正ObjectRepresentation的构造函数问题
OneCoder 在Restlet 2.1.4中 匪夷所思的ObjectRepresentation的构造函数中,提到过在使用2.1.4的时候遇到的异常 Exception in thread "main" java.lang.IllegalArgumentExcept...
Restlet 客户端连接超时问题解决
使用Restlet进行同步请求,有时可能处理的时间会很长所以需要客户端进行较长时间的等待。从API中查得客户端的设置方式如下: 不过,设置后,OneCoder经测试却发现无效。无论socketTimeout设置为多少。均会在1分钟左右超时。 这好像是由于Restlet默...
OneCoder
始于 2012持续记录 C++ GESP/CSP 信奥算法、Java 服务端架构与 Python 工程实战。官方唯一域名:coderli.com