日期:2014-05-20  浏览次数:20884 次

跪求高手!把文件中的数据读取之后放到list中出现的问题诡异悬疑
程序是这样的把D:/test/in.txt中的数据通过getIn(List<Byte> list, FileInputStream fin)方法放到一个list<Byte>的容器中
public class FileInputStreamDemo {
/**
* 用来读取文件数据
* 存入到list容器中
*/
public List<Byte> getIn(List<Byte> list, FileInputStream fin) {

try {
int temp=fin.read();
while (temp != -1) {
list.add((byte)temp);
}
/*
* while (fin.read() != -1) {
list.add((byte)fin.read());

*/
System.out.println(list);
} catch (IOException e1) {
e1.printStackTrace();
}finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(list);
return list;
}

/**
* 执行数据的copy

* @param list
* @param fout
*/
public void toCopyStream(List<Byte> list, FileOutputStream fout) {
byte[] b = new byte[list.size()];
for (int i = 0; i < list.size(); i++) {
b[i] = list.get(i);
}
try {
fout.write(b);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static void main(String[] args) {
FileInputStream fin = null;
FileOutputStream fout = null;
try {
fin = new FileInputStream("D:/test/in.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fout = new FileOutputStream("D:/test/out.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<Byte> list = new ArrayList<Byte>();
FileInputStreamDemo fisd = new FileInputStreamDemo();
fisd.getIn(list, fin);
System.out.println(list);
fisd.toCopyStream(list, fout);
}

}

错误是:Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
但是当我把getIn(List<Byte> list, FileInputStream fin)中的
int temp=fin.read();
while (temp != -1) {
list.add((byte)temp);}
换成注释中的/*
* while (fin.read() != -1) {
list.add((byte)fin.read());

*/
时没有错误了,但是又出现了这种情况;当文件D:/test/in.txt中放aaa时又
list打印出来是[97,-1]

跪求高手,我该如何改啊!!!!!!!!!



------解决方案--------------------
因为无限死循环了。。。。。。
while (temp != -1) {
list.add((byte)temp);
}
你这句话,循环如何结束呢?最终必然是list用完所有可用内存然后挂掉。


------解决方案--------------------
前面的是进入死循环了。

下面的97是ACSII码