java中按指定字节大小切割文件

package cn.itcast.codetabletest.demo;
/**
 * 按指定字节大小切割文件
 * */
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class CodeTableDemo {

	public static void main(String[] args) throws IOException {
		
		/*String str="ab你好cd谢谢";
		int len=str.getBytes("gbk").length;
		for(int x=0;x<len;x++) {
			System.out.println("截取"+(x+1)+"个字节的结果是:"+cutstringByByte(str,x+1));
		}
		*/	
		String str="ab你好cd谢谢";
		int len=str.getBytes("utf-8").length;
		for(int x=0;x<len;x++) {
			System.out.println("截取"+(x+1)+"个字节的结果是:"+cutstringByU8Byte(str,x+1));
		}
	
	}

	
	public static String cutstringByU8Byte(String str, int len) throws IOException {
		byte[]by=str.getBytes("utf-8");
		int t=0;
		for(int x=len-1;x>=0;x--) {
			if(by[x]<0)
				t++;
			else
				break;
		}
		if(t%3==0)
			return new String(by, 0, len,"utf-8");
		else
			if(t%3==1)
				return new String(by, 0, len-1,"utf-8");
			else 
				return new String(by, 0, len-2,"utf-8");
	}

	public static String cutstringByByte(String str, int len) throws IOException {
		byte[]by=str.getBytes("gbk");
		int t=0;
		for(int x=len-1;x>=0;x--) {
			if(by[x]<0)
				t++;
			else
				break;
		}
		if(t%2==0)
			return new String(by, 0, len,"gbk");
		else
			return new String(by, 0, len-1,"gbk");
	}
}

 

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页