Skip to content

Commit

Permalink
Add method to handle NIO channel
Browse files Browse the repository at this point in the history
  • Loading branch information
looly committed Aug 30, 2014
1 parent e9aa472 commit f2fc95d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
38 changes: 37 additions & 1 deletion src/main/java/com/xiaoleilu/hutool/CharsetUtil.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.xiaoleilu.hutool;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

import com.xiaoleilu.hutool.exceptions.UtilException;

Expand Down Expand Up @@ -42,11 +44,13 @@ public static String convert(String source, String srcCharset, String newCharset
}

/**
* 将编码的byte数据转换为字符串
* 将编码的byte数据转换为字符串<br>
* 已废弃,请使用StrUtil.decode
* @param data 数据
* @param charset 字符集,如果为空使用当前系统字符集
* @return 字符串
*/
@Deprecated
public static String str(byte[] data, String charset) {
if(data == null) {
return null;
Expand All @@ -62,4 +66,36 @@ public static String str(byte[] data, String charset) {
throw new UtilException(e);
}
}

/**
* 将编码的byteBuffer数据转换为字符串
* @param data 数据
* @param charset 字符集,如果为空使用当前系统字符集
* @return 字符串
*/
public static String str(ByteBuffer data, String charset){
if(data == null) {
return null;
}

Charset cs;

if(StrUtil.isBlank(charset)) {
cs = Charset.defaultCharset();
}else {
cs = Charset.forName(charset);
}

return cs.decode(data).toString();
}

/**
* 字符串转换为byteBuffer
* @param str 字符串
* @param charset 编码
* @return byteBuffer
*/
public static ByteBuffer toByteBuffer(String str, String charset) {
return ByteBuffer.wrap(StrUtil.encode(str, charset));
}
}
13 changes: 13 additions & 0 deletions src/main/java/com/xiaoleilu/hutool/IoUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

import com.xiaoleilu.hutool.exceptions.UtilException;
Expand Down Expand Up @@ -120,6 +121,18 @@ public static String getString(InputStream in, String charset) throws IOExceptio
return content.toString();
}

/**
* 从FileChannel中读取内容
* @param fileChannel 文件管道
* @param charset 字符集
* @return 内容
* @throws IOException
*/
public static String getString(FileChannel fileChannel, String charset) throws IOException {
final MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()).load();
return CharsetUtil.str(buffer, charset);
}

/**
* String 转为 流
* @param content 内容
Expand Down

0 comments on commit f2fc95d

Please sign in to comment.