关于一个从文件中读取内容的编程问题
这里可以用FileInputStream 或者FileReader或RandomAccessFile流,分别用这三个流写了三个对应的方法。具体代码如下:
private static void fileInputStream() {
File f = new File("F:/ecilpse/workplace/io", "a.txt");
try {
byte[] b = new byte[100];
FileInputStream in = new FileInputStream(f);
int n = 0;
while ((n = in.read(b, 0, 100)) != -1) {
String str = new String(b, 0, n);
System.out.println(str);
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void fileReader() {
File f = new File("F:/ecilpse/workplace/io", "a.txt");
try {
char[] b = new char[2];
FileReader in = new FileReader(f);
int n = 0;
while ((n = in.read(b, 0, 1)) != -1) {
String str = new String(b, 0, n);
System.out.println(str);
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void randomAccessFile() throws NullPointerException {
File f = new File("F:/ecilpse/workplace/io", "a.txt");
RandomAccessFile inAndOut;
try {
inAndOut = new RandomAccessFile(f, "rw");
long length = inAndOut.length();
long position = 0;
inAndOut.seek(position);
while (position < length) {
String str = inAndOut.readLine();
byte b[] = str.getBytes("iso-8859-1");
str = new String(b);
position = inAndOut.getFilePointer();
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
1. 比较后发现 用FileInputReader和FileReader流最终都是构建一个字节数组,这样new一个String对象,而R安东AccessFile是不需要的,就像上面代码所写的,直接用流对象读取,只不过这里需要处理中文字符乱码问题。同时也是在while循环中生成了字节数组。三种方法比较后发现,前两种方法的字节流数组需要伴随着while循环一直的创建,不过现在我刚刚发现了一个问题,其实while循环中的String对象也是需要不停的创建,只不过没有n的限制,我想这样代价会小点。而且整个代码量也很少。如果再加上向文件中写入,再读出,那么整个代码量就会更大。
2. 另外在randomAccessFile方法中,由于设置了while(position<length),中间的<号换成=号的话 会抛出NullPointerException,之后在改的过程中,无论是抛出异常还是add catch()方法也不能解决,看来还是代码里面有问题。这里position随着文本的读入会增大,知道与length相等,如果改为=号那么while循环最后结束的条件就有问题,当position=length时,文本已经读完了,但是while循环条件成立,所以还是要执行循环体的内容,因此会抛出NullPointerException。
本文对比了FileInputStream、FileReader和RandomAccessFile三种文件读取方式,并提出改进策略以减少内存开销。
2122

被折叠的 条评论
为什么被折叠?



