
contentSummanry = contentSummanrysubstring(0,100); 这就是说我要截取前面一百个字符
同学 这是最好的截取了 你试试
contentSummanry就是你要去里面截取的字符串 看看这里吧:
public class CutString {
/
判断是否是一个中文汉字
@param c
字符
@return true表示是中文汉字,false表示是英文字母
@throws UnsupportedEncodingException
使用了JAVA不支持的编码格式
/
public static boolean isChineseChar(char c)
throws UnsupportedEncodingException {
// 如果字节数大于1,是汉字
// 以这种方式区别英文字母和中文汉字并不是十分严谨,但在这个题目中,这样判断已经足够了
return StringvalueOf(c)getBytes("GBK")length > 1;
}
/
按字节截取字符串
@param orignal
原始字符串
@param count
截取位数
@return 截取后的字符串
@throws UnsupportedEncodingException
使用了JAVA不支持的编码格式
/
public static String substring(String orignal, int count)
throws UnsupportedEncodingException {
// 原始字符不为null,也不是空字符串
if (orignal != null && !""equals(orignal)) {
// 将原始字符串转换为GBK编码格式
orignal = new String(orignalgetBytes(), "GBK");
// 要截取的字节数大于0,且小于原始字符串的字节数
if (count > 0 && count < orignalgetBytes("GBK")length) {
StringBuffer buff = new StringBuffer();
char c;
for (int i = 0; i < count; i++) {
// charAt(int index)也是按照字符来分解字符串的
c = orignalcharAt(i);
buffappend(c);
if (CutStringisChineseChar(c)) {
// 遇到中文汉字,截取字节总数减1
--count;
}
}
return bufftoString();
}
}
return orignal;
}
public static void main(String[] args) {
// 原始字符串
String s = "我ZWR爱JAVA";
Systemoutprintln("原始字符串:" + s);
try {
Systemoutprintln("截取前1位:" + CutStringsubstring(s, 1));
Systemoutprintln("截取前2位:" + CutStringsubstring(s, 2));
Systemoutprintln("截取前4位:" + CutStringsubstring(s, 4));
Systemoutprintln("截取前6位:" + CutStringsubstring(s, 6));
} catch (UnsupportedEncodingException e) {
eprintStackTrace();
}
}
}
import javaioFile;
import javaioRandomAccessFile;
/
2016年8月31日下午7:00:37
@author 3306 TODO 计算字节数
/
public class FileUtil {
public static void main(String[] args) {
String filePath = "d:/testtxt";// d盘必须存在testtxt文件
readEachLine(filePath);
}
/
打印文件每一行的字节数
@param filePath
文件路径
/
private static void readEachLine(String filePath) {
try {
File file = new File(filePath);
if (fileexists()) {// 文件存在
RandomAccessFile accessFile = new RandomAccessFile(file, "r");// 只赋予读的权限
String line = "";
long lineIndex = 1;
while (null != (line = accessFilereadLine())) {
Systemoutprintln("line" + (lineIndex++) + ": " + linegetBytes()length);// 打印行号和字节数
}
accessFileclose();
}
} catch (Exception e) {
eprintStackTrace();
}
}
}
import javaioFile;
import javaioFileNotFoundException;
import javaioFileReader;
import javaioFileWriter;
import javaioIOException;
public class TestFile {
public static void main(String[] args) throws IOException{
int num = 0;
int c = 0;
File f = new File("c://atxt");
FileReader fr = new FileReader(f);
FileWriter fw = new FileWriter("c://btxt");
while((c = frread())!=-1){
Systemoutprint((char)c);
num++;
}
Systemoutprintln();
Systemoutprintln("文件长度是" + num);
}
}
给你代码吧 这样的方法能够算长度
short 两字节 int 四字节 long int 8字节
char 两字节 float 32字节 double 64字节
1个字节占8位
以上就是关于java字符串字节长度截取问题全部的内容,包括:java字符串字节长度截取问题、java读取txt文件每一行多少个字节、java用什么方法可以求一个文件的长度等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)