我需要将给定的文本文件拆分为相同大小的块并将它们存储到数组中。输入是一组同一文件夹中的许多文本文件。我使用以下代码:java代码根据块大小将文本文件拆分为块
int inc = 0;
File dir = new File("C:\\Folder");
File[] files = dir.listFiles();
for (File f : files) {
if(f.isFile()) {
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(f));
String line;
while ((line = inputStream.readLine()) != null) {
String c[] = splitByLength(line, chunksize);
for (int i=0;i<c.length;i++) {
chunk[inc] = c[i];
inc++;
}
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
public static String[] splitByLength(String s, int chunkSize) {
int arraySize = (int) Math.ceil((double) s.length()/chunkSize);
String[] returnArray = new String[arraySize];
int index = 0;
for(int i=0; i<s.length(); i=i+chunkSize) {
if(s.length() - i < chunkSize) {
returnArray[index++] = s.substring(i);
}
else {
returnArray[index++] = s.substring(i, i+chunkSize);
}
}
return returnArray;
}
这里块值存储在“块”数组中。但是,这里的问题是因为我已经使用readLine()命令来解析文本文件,所以只有当块大小小于一行中的字符数时,所得到的结果才是正确的。可以说每行有10个字符,文件中的行数是5.然后,如果我提供大于10的任何值的块大小,它总是将每个块中的每行分割成10个块。
例如,考虑具有以下内容的文件,
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
如果块大小= 5然后,
ABCDE | fghij | abcde | fghij | abcde | fghij | abcde | fghij | abcde | fghij |
if chunk size = 10 then,
abcdefghij | abcdefghij | abcdefghij | abcdefghij | abcdefghij |
如果块大小> 10,然后还我的代码只提供和以前一样,
ABCDEFGHIJ | abcdefghij | abcdefghij | abcdefghij | abcdefghij |
我试过使用RandomAccessFile和FileChannel,但我无法获得所需的结果... 任何人都可以帮助我解决这个问题吗?谢谢..
如果最后的块小于chunk_size,请在其末尾追加新读取的字符串。然后照常继续。 – usr2564301 2014-10-12 12:13:08