2014-10-17 69 views
0

我有一个递归函数,它将Bytes数组(作为参数读取)作为参数,然后尝试将其分为两部分以进行递归调用。拆分之前从文件中读取的字节数组

的文件格式是例如这样的:

word1 word2 
word3 word4 
    .... 
word97 word98 
word99 word100 

所以,阅读它,我用这个代码:

byte[] content = new byte[(int) file.length()]; 
FileInputStream fileInputStream = null; 

fileInputStream = new FileInputStream(file); 
fileInputStream.read(content); 

但后来我想内容阵列分成两个部分每个代表原始文件的一半。例如,如果原始文件包含四行,那么firstHalf数组将包含前两行,而secondHalf数组则是原始文件的最后两行。

我用这个:

int halfTheLengthOfContent = (int) Math.ceil(content.length/2.0); 
firstHalf = Arrays.copyOfRange(content, 0, halfTheLengthOfContent) 
and 

secondHalf = Arrays.copyOfRange(content, halfTheLengthOfContent + 1, content.length) 

但由于导致阵列不符合我想要的东西这是行不通的。 我想要的是,第一个哈夫阵列将包含相同的内容,如果我已经这样做(这次file1包含原始文件的内容的前半部分,file2的后半部分):

byte[] firstHalf = new byte[(int) file1.length()]; 
FileInputStream fileInputStream = null; 

fileInputStream = new FileInputStream(file1); 
fileInputStream.read(firstHalf); 

byte[] secondHalf = new byte[(int) file2.length()]; 
FileInputStream fileInputStream = null; 

fileInputStream = new FileInputStream(file2); 
fileInputStream.read(secondHalf); 

例如,如果原始文件是这样的:

word1 word2 
word3 word4 
word5 word6 
word7 word8 

然后file1的是:

word1 word2 
word3 word4 

和file2是这样的:

word5 word6 
word7 word8 

你能帮帮我吗?

+0

'halfTheLengthOfContent'是什么? – jhamon 2014-10-17 07:18:53

+0

您需要不断尝试读取,直到读完所有字节。调用它可能会读取整个文件,也可能不读取整个文件,这就是为什么它会返回一个“int”。 – 2014-10-17 07:19:36

+1

有两件事:1.你说的是“字符串”,它是字符序列,但你读取字节;这里有矛盾; 2.为什么不使用'ByteBuffer's?特别是'FileChannel.map()'的结果?这将允许_not_不断复制内容 – fge 2014-10-17 07:19:51

回答

3

“字节”和“行”的概念不能很好地协同工作。

字节是文件的核心元素,每个字符可能有一个字节。可能有两个。

将包含整个文件的byte[]拆分成两个偶数部分不太可能导致分裂为包含相同行数的两个byte[]。拆分甚至不太可能在换行上,更可能在一个词的中间。

您需要的是将文件读取为并对其进行操作。例如:

final List<String> lines = Files.readAllLines(Paths.get("path", "to", "file")); 
final int middle = lines.size()/2; 
final List<String> firstHalf = lines.subList(0, middle); 
final List<String> secondHalf = lines.subList(middle, lines.size()); 

如果文件4线则middle2。上半场将包含线路0, 1,下半场将包含线路2, 3。请记住List为零索引,sublist排除上限。

奇数行后半部分将包含额外的元素。