2014-10-12 56 views
-3

我需要将给定的文本文件拆分为相同大小的块并将它们存储到数组中。输入是一组同一文件夹中的许多文本文件。我使用以下代码: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,但我无法获得所需的结果... 任何人都可以帮助我解决这个问题吗?谢谢..

+0

如果最后的块小于chunk_size,请在其末尾追加新读取的字符串。然后照常继续。 – usr2564301 2014-10-12 12:13:08

回答

0

这是因为BufferedReader.readLine()只读取一行而不是整个文件。

我假定换行符\r\n是不正常的内容,您感兴趣的部分。

也许没有什么帮助。

// ... 
StringBuilder sb = new StringBuilder(); 
String line; 
while ((line = inputStream.readLine()) != null) { 
    sb.append(line); 

    // if enough content is read, extract the chunk 
    while (sb.length() >= chunkSize) { 

     String c = sb.substring(0, chunkSize); 
     // do something with the string 

     // add the remaining content to the next chunk 
     sb = new StringBuilder(sb.substring(chunkSize)); 
    } 
} 
// thats the last chunk 
String c = sb.toString(); 
// do something with the string 
+0

它适用于小文件,但当我使用大型内容文件时,它显示Java堆空间错误.. – 2014-10-12 15:31:27

+0

好吧,我更新了我的答案。现在它将从文件中读取,直到达到chunkSize。然后发生分割,并读取下一个块。 – DirkNM 2014-10-12 15:49:15

+0

我不明白你的代码是如何工作的?你已经在两个地方叫了splitByLength .. – 2014-10-12 15:58:16

相关问题