将读取的文本字符按指定长度分割:
package Demo;
import java.io.*;
import java.util.*;
public class code
{
public static void main(String[] args) throws IOException {
//通过字符数组进行读取
FileReader fr = new FileReader("abc.txt");
//定义一个字符数组,用于存储读到的字符
//该read(char[])返回的是读到字符的个数
char[] buf = new char[1024];//2k
int num = 0,length=9;//length:指定长度
String inputString = "";
while((num=fr.read(buf))!=-1) {
inputString = new String(buf,0,num);
}
//把原始字符串分割成指定长度的字符串列表
int size = inputString.length() / length;
if (inputString.length() % length != 0) {
size += 1;
}
//把原始字符串分割成指定长度的字符串列表
List<String> list = new ArrayList<String>();
for (int index = 0; index < size; index++) {
String childStr=null;
if(index==0)
childStr = substring(inputString,index * length,(index + 1) * length);
else
childStr = substring(inputString,index * length-index+1,(index + 1) * length-index);
list.add(childStr);
}
//遍历List集合
ListIterator l=list.listIterator();
while(l.hasNext()){
Object obj=l.next();
System.out.println(obj);
}
fr.close();
}
//分割字符串,如果开始位置大于字符串长度,返回空
public static String substring(String str, int f, int t) {
//f:开始位置 t:结束位置
if (f > str.length())
return null;
if (t > str.length()) {
return str.substring(f, str.length());
} else {
return str.substring(f, t);
}
}
}