内存溢出怎么办?请大家帮忙优化一下
这个程序是获取某个盘(如C盘)的所有文件的路径。如果文件比较多的话,就会出现内存溢出,大家帮忙看看怎么优化好呢~!
[code=Java][/code]package test.io;
import java.io.*;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
public class IoAllDemo {
	StringBuffer sbf = new StringBuffer();
	int count = 0;
	public static void main(String[] args) throws Exception {
		IoAllDemo al = new IoAllDemo();
		File newFile = new File("F:" + File.separator + "test.txt");
		newFile.createNewFile();
		long lm = newFile.lastModified();
		Date d = new Date(lm);
		DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
				DateFormat.MEDIUM);
		String str = df.format(d);		
		al.getName(new File("D:\\"));
		String name = al.sbf.toString();
		FileOutputStream fos = new FileOutputStream(newFile);
		fos.write(name.getBytes());
		fos.write(str.getBytes());
		fos.flush();
		fos.close();		
		System.out.println("test.txt最后更改时间" + str);
	}
	public void getName(File file){		
		if(file.isFile()){
			sbf.append(count+"-->"+file.getPath()+"  ");
		}
		if (file.isDirectory()) {
			File list[] = file.listFiles();
			if (list != null) {
				for (File ls : list) {
					System.out.println(count+"-->"+ls);
					getName(ls);
					count++;
				}
			}
		}
	}
}
------解决方案--------------------个人认为:
  递归时不是用一个StringBuffer连接保存,而是递归一个文件就写一次文件。
------解决方案--------------------在main方法中创建 FileOutputStream ,并做为参数传给getName方法。getName中直接对这个流进行写操作。最后到main方法里关闭流。
------解决方案--------------------用Stringbuffer连接保存,递归每一个文件夹,写出的时候使用
 FileOutputStream fos = new FileOutputStream(newFile,true); 这样可以保证文件不会被重新建,被覆盖重写。同时保证内存不溢出
------解决方案--------------------#1 + #5楼,楼主的问题应该能搞定了。