我有一组大文件(每个文件大约 2-3GB),我需要使用 InputStream
读取它并将其部分输出到新文件。
//this is just for example
int size=100;
String src="pathtofile";
OutputStream os = null;
Inputstream is = new FileInputStream(new File(src));
byte[] buffer = new byte[size];
byte[] bufferis = getBytesFromIS(is);
buffer=Arrays.copyOfRange(bufferis,0,buffer.length);
String tempstr=new String(buffer);
byte[] tempBytes=Arrays.copyOfRange(bufferis, buffer.length,is.available());
os = new FileOutputStream(new File(dest));
copy(new ByteArrayInputStream(tempBytes), os); //function writing to file
这适用于小文件,但在大文件上使用时,我不断收到 OutOfMemoryError
,即使我设置 -Xmx6114m
,仍然得到 OutOfMemoryError
.
最佳答案
最大数组长度略小于Integer.MAX_VALUE
,即大约2e9
。因此,您无法将整个内容读入 byte[]
中,而必须使用其他内容。 ByteByffer
可能是最快的解决方案(内存映射文件)。
关于java - InputStream读取部分文件并输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41228705/