【发布时间】:2014-12-07 02:08:03
【问题描述】:
我需要将给定的文本文件分成大小相等的块并将它们存储到一个数组中。输入是同一文件夹中的一组许多文本文件。我为此使用以下代码:
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 |
如果块大小 = 10 那么,
abcdefghij | abcdefghij | abcdefghij | abcdefghij | abcdefghij |
如果块大小 > 10 那么我的代码也只提供与以前相同的功能,
abcdefghij | abcdefghij | abcdefghij | abcdefghij | abcdefghij |
我尝试使用 RandomAccessFile 和 FileChannel,但无法获得所需的结果... 谁能帮我解决这个问题?谢谢你。。
【问题讨论】:
-
如果最后一个块小于你的块大小,将新读取的字符串附加到它的末尾。然后照常继续。