一、创建大文件
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class CreateFile {
//创建1GB的大文件
public static void create(File file) throws IOException {
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
while(file.length()<(1024*1024*1024)){
String temp=createTemp();
bufferedWriter.write(temp);
}
bufferedWriter.close();
}
//创建1KB的字符串
public static String createTemp(){
String temp="";
while(temp.length()<1024) {
char random = createRandom(65, 122);//通过Ascii码来创建随机字符串,比从字符串中截取字符串来构建高效
temp += random;
}
return temp;
}
//创建min和max范围内的随机字符
public static char createRandom(int min,int max){
Random random = new Random();
int i = random.nextInt(max-min+1)+min;
char ch=(char)i;
return ch;
}
public static void main(String[] args) throws IOException {
long starttime = System.currentTimeMillis();
File file = new File("D:\\a.txt");
file.createNewFile();
create(file);
long endtime = System.currentTimeMillis();
System.out.println("程序执行时间"+(endtime-starttime));//程序执行时间325737
}
}
二、读取大文件
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFile {
public static void read(File file) throws IOException {
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[1024*1024*1024];
int length=0;
while((length=fileInputStream.read(bytes))!=-1){
System.out.println(new String(bytes,0,length));
}
fileInputStream.close();
}
public static void main(String[] args) throws IOException {
long starttime = System.currentTimeMillis();
File file = new File("D:\\a.txt");
read(file);
long endtime = System.currentTimeMillis();
System.out.println("运行时间为:"+(endtime-starttime));//缓冲数组为1kb运行时间为:36440;缓冲数组为1MB运行时间为:22641
//缓冲数组为1GB报java.lang.OutOfMemoryError,因为默认的Java虚拟机最大内存仅为64MB
//缓冲数组为60MB运行时间为:30180
//缓冲数组为30MB运行时间为:27764
}
}
导致OutOfMemoryError异常的常见原因有以下几种:
- 内存中加载的数据量过于庞大,如一次从数据库取出过多数据;
- 集合类中有对对象的引用,使用完后未清空,使得JVM不能回收;
- 代码中存在死循环或循环产生过多重复的对象实体;
- 使用的第三方软件中的BUG;
- 启动参数内存值设定的过小;
此错误常见的错误提示:
- tomcat:java.lang.OutOfMemoryError: PermGen space
- tomcat:java.lang.OutOfMemoryError: Java heap space
- weblogic:Root cause of ServletException java.lang.OutOfMemoryError
- resin:java.lang.OutOfMemoryError
- java:java.lang.OutOfMemoryError
解决方法:
- 增大jvm内存大小
1)在执行某个class文件时候,可以使用java -Xmx256M aa.class来设置运行aa.class时jvm所允许占用的最大内存为256M
2)对tomcat容器,可以在启动时对jvm设置内存限度
3)对resin容器,同样可以在启动时对jvm设置内存限度。 - 优化程序,释放垃圾
主要包括避免死循环,应该及时释放种资源:内存, 数据库的各种连接,防止一次载入太多的数据
对tomcat,可以在catalina.bat中添加:
set CATALINA_OPTS=-Xms128M -Xmx256M
set JAVA_OPTS=-Xms128M -Xmx256M
或者把%CATALINA_OPTS%和%JAVA_OPTS%代替为-Xms128M -Xmx256M
对对resin容器,在bin文件夹下创建一个startup.bat文件,内容如下:
@echo off
call "httpd.exe" "-Xms128M" "-Xmx256M"
:end
其中”-Xms128M”为最小内存,”-Xmx256M”为最大内存