0

我正在努力学习 Java。我有一小段代码试图读取和写入输入流。但是有一句话我就是不明白意思。

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("xanadu.txt");
            out = new FileOutputStream("outagain.txt");
            int c;

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

这部分的含义是什么:?

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

变量C实际上做了什么?

该程序如何真正发挥作用?

变量是否C从输入流文件中读取,并且在读取之后,正在读取的部分是否已从输入流文件中清除并消除?

有人可以通过逐行解释此代码通常的作用来帮助我吗?

4

4 回答 4

0

根据JavaDoc

回报:

数据的下一个字节,如果到达文件末尾,则为 -1。

这意味着:

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

意思是直到输入流还没有找到文件结尾,也就是文件里还有字符,继续读。读取下一个数据字节后,将其写入输出流。

于 2012-11-30T06:05:54.443 回答
0

- FileInputStream and FileOutputStream are used when you need to read from and write into the file respectively in the form of bytes....

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

- What you are doing is that, you are reading the data in the file xanadu.txt in the form of bytes and then writing it to file outagain.txt.

- And it will continue till in.read() returns -1, as -1 will indicate the EOF (end of file).

于 2012-11-30T06:07:21.803 回答
0

What is the meaning of this part :?

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

Reads byte by byte from xanadu.txt file and output it to outagain.txt also byte by byte.

What does variable C actually do?

Java is case-sensitive, so it c not C. It has the value of byte read from input file.

于 2012-11-30T06:08:40.680 回答
0
while ((c = in.read()) != -1) {
        out.write(c);}

In the above code as per the JavaDocs the method in.read() returns -1 if it reaches the end of the file so what it means is that you need to stay in the loop untill the read method does not return -1

How does the program really function?

Now coming to this part you are basically reading the file as rawbytes using FileInputStream and writing it as a file again using FileOutputStream where the above while loop determines you write the whole file till the end

Does the variable C read from the input stream file and after it has read, the part which is being read it's cleaned and eliminated from the input stream file?

The method read() Reads a byte of data from the input stream and returns it so you have to write the data simultaneously as you read and yes the previous byte that has been read would be removed as it reads a new byte

FileInputStream is meant for reading streams of raw bytes such as Image data. For reading streams of characters, consider using FileReader

于 2012-11-30T06:08:45.827 回答