求教关于java 字节流的问题
首先说说需要的功能,
对一个文件进行解析,需要每1024个字节作为一部分,
能够实现读取文件中任意第几个1024个字节的字符串。
对于1024字节的字符串以每个字节为一个元素存储为String []。
下面是我的实现算法
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
public class Filedecode {
public static void main(String[] args) {
//读取1.txt文件,每1024字节作为一部分,从第12个1024字节开始,一直读取8个。
readFile("D:\\1.txt",12,8);
}
public static ArrayList<String[]> readFile(String path, int startindex,
int length) {
ArrayList<String[]> list = null;
try {
File file = new File(path);
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(file));
list = new ArrayList<String[]>(length);
byte[] a = new byte[1024];
String[] str = new String[1024];
int count = -1;
int com = 0;
int end = startindex + length;
while ((count = in.read(a)) != -1 && com < end) {
if (startindex == com) {
//将字节数组转字符
str = StringTool.byteTohex(a);
list.add(str);
str = null;
com++;
startindex++;
} else {
com++;
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return list;
}
}
用我上面的方法实现有两个问题,
1. list中存放的字符不能太多,多了就会报内存溢出,
2. 也会出现性能问题,如果要读第1000个1024字节的字符串,
需要先把前面的999个都读一遍,当要读取的文件很大时,读取速度非常慢。
//求教各位有没有更好的算法实现我的功能,本人是新人积分不多,只有60分,都给大家。