How do FileInputStream and FileOutputStream work in Java?

I read about all the input / output streams in java on Java Tutorials Docs Docs . The script writer uses this example:

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();
            }
        }
    }
}

xanadu.txt File details:

In Xanadu did Kubla Khan
A stately pleasure-dome decree:
Where Alph, the sacred river, ran
Through caverns measureless to man
Down to a sunless sea.

Exit to the outagain.txt file:

In Xanadu did Kubla Khan
A stately pleasure-dome decree:
Where Alph, the sacred river, ran
Through caverns measureless to man
Down to a sunless sea.
  • Why do authors use int ceven if we read characters?

  • Why use -1during a condition?

  • How out.write(c);to convert method intto characters again?

+4
source share
2 answers

1: Now I want to ask why the author uses int c? even we read characters.

FileInputStream.read() int. , int . . , , int byte.

2: -1 ?

, -1.

3: out.write(c); int ? outagain.txt

FileOutputStream.write() int. int , , 24 int , - : a int Java 32 . 24 , 8- , .

Javadocs . :

read:

. int 0 255. , , -1. , , .

write:

. , . , , b. 24 b .

+5

.

http://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html#read()

public int read()           IOException . , .

: InputStream

: -1, .

int - . , .

1) char int, ascii int.

, ascii- https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

2) -1, . .

3) ascii- , char .

+1

Source: https://habr.com/ru/post/1609084/


All Articles