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

Java IO 操作问题
Java code
import java.io.*;
public class IOTest {
    public static void main(String[] args) throws Exception {
        File f1 = new File("x1.txt");
        File f2 = new File("x2.txt");
        InputStream is = new FileInputStream(f1);
        OutputStream os = new FileOutputStream(f2, true);
        byte[] buf = new byte[1024];
        int len = 0;
        while((len=is.read(buf)) != 0) {
            if(len > 0) {
                os.write(buf,0,len);
            }
            if(f2.length() == f1.length()*3) {
                break;
            }
        }
        os.close();
        is.close();
    }
}


x1.txt的内容如下:
something is wrong.
x2.txt的内容是什么啊?为什么?
每次读指针读到末尾会自动跳到0位置?

------解决方案--------------------
while((len=is.read(buf)) != 0) { //改成-1
当读取不到字节的时候,返回-1,如果读取到字节返回相应的字节数(>0),所以用!=0作为循环条件,死循环了

------解决方案--------------------
((len=is.read(buf)) != 0)

这个条件的话 不是x2.txt的内容是什么只能是something is wrong么 因为读不到就不循环了 

 if(f2.length() == f1.length()*3) {
break;
}
这个不可能执行
------解决方案--------------------
将0改为-1后,x2.txt中只可能是一行“something is wrong.”。
为什么会输出3行,原因就是:你是以追加方式写入文件的,而你是总共执行了3次程序呗,了解?
------解决方案--------------------
Java code

import java.io.*;
public class IOTest {
    public static void main(String[] args) throws Exception {
        File f1 = new File("x1.txt");
        File f2 = new File("x2.txt");
        InputStream is = new FileInputStream(f1);
        OutputStream os = new FileOutputStream(f2, true);
        byte[] buf = new byte[1024];
        int len = 0;
        while((len=is.read(buf)) != -1) {
            os.write(buf,0,len);
        }
        os.flush();
        os.close();
        is.close();
    }
}

------解决方案--------------------
x2的结果是一个something is wrong.
因为你读取了x1的内容,并写入了x2.
其余的同上。不过os.flush()可以不写,因为os.close()等于flush
------解决方案--------------------
for(int i=0;i<3;i++){
while((len=is.read(buf)) != -1) {
os.write(buf,0,len,new);
}

}
就可以实现三行了
------解决方案--------------------
import java.io.*;
public class IOTest {
public static void main(String[] args) throws Exception {
File f1 = new File("x1.txt");
File f2 = new File("x2.txt");
InputStream is = new FileInputStream(f1);
OutputStream os = new FileOutputStream(f2, true);
byte[] buf = new byte[1024];
int len = 0;
while((len=is.read(buf)) != 0) {//修改成-1是没有找到内容,不等于-1说明有内容,这样应该就行了吧,你再试试 while((len=is.read(buf)) != -1) {
if(len > 0) {
os.write(buf,0,len);
}
if(f2.length() == f1.length()*3) {
break;
}
}
os.close();
is.close();
}
}