
import java.io.FileNotFoundException
import java.io.FileReader
import java.io.IOException
import java.io.RandomAccessFile
import java.util.Scanner
public class TestPrint {
public static void main(String[] args) throws IOException {
String path = "你要读的文件的路径"
RandomAccessFile br=new RandomAccessFile(path,"rw")//这里rw看你了。要是之都就只写r
String str = null, app = null
int i=0
while ((str = br.readLine()) != null) {
i++
app=app+str
if(i>=100){//假设读取100行
i=0
// 这里你先对这100行 *** 作,然后继续读
app=null
}
}
br.close()
}
}
当我们遇到文本文件体积很大时,比如超过几十M甚至几百M几G的大文件,用记事本或者其它编辑器打开往往不能成功,因为他们都需要把文件内容全部放到内存里面,这时就会发生内存溢出而打开错误,遇到这种情况我们可以使用PHP的文件读取函数file_get_contents()进行分段读取。函数说明
string
file_get_contents
(
string
$filename
[,
bool
$use_include_path
[,
resource
$context
[,
int
$offset
[,
int
$maxlen
]]]]
)
和
file()
一样,只除了
file_get_contents()
把文件读入一个字符串。将在参数
offset
所指定的位置开始读取长度为
maxlen
的内容。如果失败,file_get_contents()
将返回
FALSE。
file_get_contents()
函数是用来将文件的内容读入到一个字符串中的首选方法。如果 *** 作系统支持还会使用内存映射技术来增强性能。
应用:
复制代码
代码如下:
$str
=
$content=file_get_contents("2.sql",FALSE,NULL,1024*1024,1024)
echo
$str
如果针对较小文件只是希望分段读取并以此读完可以使用fread()函数
复制代码
代码如下:
$fp=fopen('2.sql','r')
while
(!feof($fp)){
$str.=fread($fp,
filesize
($filename)/10)//每次读出文件10分之1
//进行处理
}
echo
$str
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)