2013-05-27 12 views
2
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 

public class CopyBytes { 
public static void main(String[] args) throws IOException { 

    FileInputStream in = null; 
    FileOutputStream out = null; 

    try { 
     in = new FileInputStream("C:\\int.txt"); 
     out = new FileOutputStream("C:\\out.txt"); 
     int c; 

     while ((c = in.read()) != -1) { 
      out.write(c); 
     } 
    } finally { 
     if (in != null) { 
      in.close(); 
     } 
     if (out != null) { 
      out.close(); 
     } 
    } 
} 
} 

數字(-1)來自哪段代碼?字節流中字符的數字索引

while ((c = in.read()) != -1) { 
      out.write(c);. 

我試着在java教程看,但它只給我一個混亂的圖。

編輯:我的-1值更改爲-4,這引起了最後一個字符被寫了很多很多次。這是爲什麼?

回答

1

Returns: the next byte of data, or -1 if the end of the file is reached.」 - 從http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html#read()

因此,-1用於檢查當EOF(即該文件的結束)已達到和中斷環路。

+0

我知道,如果到達文件的末尾是返回-1,但是我想知道在哪裏的java得到這個數字,比如第一個字是0,第二個是1等 –

+0

嗯,我猜0和1被用作真/假..所以-1是在Java選擇...我不知道爲什麼-1,-2沒有....也許最好問一下'詹姆斯gosling'或任何人在團隊發展班上。對不起,我當然知道。另外,-1是用於套接字的常用做法,所以可以使用-1來與其他類似的類一致。 – Bill

2

-1值,標誌着該文件的末尾已到達並沒有什麼更被讀取。

Here是用於該方法的Javadoc。

0

什麼in.read()返回的是一個無符號字節[0,255],若返回-1意味着該流結束了,你不應該看它了。 in.read()永遠不會返回-4。