一个简单的读取文件为啥搞成了死循环?

 

import java.io.*;

 

public class TestMove{

private static File f1=null;

private static File f2=null;

private static FileInputStream fis=null;

private static FileOutputStream fos=null;

 

public static void main(String []args){

new TestMove("D:\\f1\\file1.txt","D:\\f2\\file2.txt").startCopy();

}

 

public TestMove(String f1,String f2){

try{

this.f1=new File(f1);

this.f2=new File(f2);

fis=new FileInputStream(this.f1);

fos=new FileOutputStream(this.f2);

}catch(IOException e){

System.out.print("wrong!");

}

 

}

public void startCopy(){

System.out.println(f1.length());

try{

 

for(int take=fis.read();take!=-1;){

System.out.print(""+take);

System.out.print(""+(char)take);

//fos.write(take);

}

fis.close();

//fos.close();

}catch(IOException e){

System.out.println("Something is wrong!");

}

}

}

2个回答

[code="java"]
for (int take = fis.read(); take != -1;take = fis.read()) {

            System.out.print("" + take);

            System.out.print("" + (char) take);

            // fos.write(take);

        }

[/code]
好晕的代码,你一直在打印第一个字符,当然死循环;
你这样copy文件,效率也不高。用BufferedInputStream

循环体也可以改为
int take;
while((take=fis.read())!=-1){
....
}

[code="java"]
for(int take=fis.read();take!=-1;){
[/code]
take就第一次赋值,以后都没有赋值!

应该这样写:
[quote]
for (int i = 0; i != -1; i = fis.read()) {
[/quote]

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问