`
danan.2009
  • 浏览: 12365 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

Java 编码解码

    博客分类:
  • java
阅读更多

Java中使用unicode编码,各操作系统有自己的默认编码,如果我们要将随机数写到文件中必须将其转化成某种编码格式的字符串,我们选择系统的默认 字符集,然后将其写入:private void gernate() {

		File file = new File(FILE_PATH);
		FileOutputStream fos = null;
		FileChannel channel = null;
		ByteBuffer byteBuffer = ByteBuffer.allocate(SIZE);
		String tem = null;
		byte[] bytes = null;
		long begin = System.currentTimeMillis();
		long end = 0;
		int num = 0;
		try {
			log.info("begin:" + begin);
			fos = new FileOutputStream(file);
			channel = fos.getChannel();
			Random random = new Random();
			for (int i = 0; i < MAX_NUM; i++) {
				num = random.nextInt(MAX_NUM);
				tem = String.valueOf(num);
				tem += i < MAX_NUM - 1 ? "中普朗克y" : "";
				bytes = tem.getBytes();
				if (byteBuffer.remaining() < bytes.length) {
					byteBuffer.flip();
					channel.write(byteBuffer);
					byteBuffer.clear();
				}
				byteBuffer.put(bytes);
			}
			byteBuffer.flip();
			channel.write(byteBuffer);
			fos.close();
			end = System.currentTimeMillis();
			log.info("end:" + end + ",use :" + (end - begin));

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

这里需要注意的是String.getBytes()方法,将unicode字符转化成系统的默认字符序列。

对于写入的文件解码问题:我们使用CharsetDecoder,完全相反的操作,解码器在其中保存一定的状态,对于解码会返回结果状态:

public void count() {
		File file = new File(FILE_PATH);
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			FileChannel channel = fis.getChannel();
			ByteBuffer byteBuffer = ByteBuffer.allocate(5);
			CharBuffer charBuffer=CharBuffer.allocate(57);
			Charset charset=Charset.defaultCharset();
			CharsetDecoder decoder = charset.newDecoder();
			CoderResult decodeResult=CoderResult.OVERFLOW;
			while(channel.read(byteBuffer)!=-1){
				byteBuffer.flip();
				while(decodeResult==CoderResult.OVERFLOW){
					 decodeResult = decoder.decode(byteBuffer, charBuffer, false);
					 System.out.println(decodeResult);
					charBuffer.flip();
					System.out.print(charBuffer.toString());
					charBuffer.clear();
				}
				if(decodeResult==CoderResult.UNDERFLOW){
					byteBuffer.compact();
					decodeResult=CoderResult.OVERFLOW;
				}
			}
			
			System.out.println();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics