我有一个递归函数,它将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
你能帮帮我吗?
'halfTheLengthOfContent'是什么? – jhamon 2014-10-17 07:18:53
您需要不断尝试读取,直到读完所有字节。调用它可能会读取整个文件,也可能不读取整个文件,这就是为什么它会返回一个“int”。 – 2014-10-17 07:19:36
有两件事:1.你说的是“字符串”,它是字符序列,但你读取字节;这里有矛盾; 2.为什么不使用'ByteBuffer's?特别是'FileChannel.map()'的结果?这将允许_not_不断复制内容 – fge 2014-10-17 07:19:51