1: Now I want to ask why writer use int c? even we are reading characters.

FileInputStream.read() returns one byte of data as an int. This works because a byte can be represented as an int without loss of precision. See this answer to understand why int is returned instead of byte.

2: The second why use -1 in while condition?

When the end of file is reached, -1 is returned.

3: How out.write(c); method convert int to again characters? that provide same output in outagain.txt file

FileOutputStream.write() takes a byte parameter as an int. Since an int spans over more values than a byte, the 24 high-order bits of the given int are ignored, making it a byte-compatible value: an int in Java is always 32 bits. By removing the 24 high-order bits, you're down to a 8 bits value, i.e. a byte.

I suggest you read carefully the Javadocs for each of those method. As reference, they answer all of your questions:

read:

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

write:

Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

Answer from Tunaki on Stack Overflow
๐ŸŒ
Coding Shuttle
codingshuttle.com โ€บ home โ€บ handbooks โ€บ java programming handbook โ€บ fileinputstream and fileoutputstream
FileInputStream and FileOutputStream | Coding Shuttle
April 9, 2025 - These classes allow us to read from and write to files in Java. FileInputStream is used to read raw byte data from a file. FileOutputStream is used to write raw byte data to a file.
๐ŸŒ
Codespindle
codespindle.com โ€บ Java โ€บ Java_fileInputStream_fileoutputstream.html
FileInputStream and FileOutputStream in Java
FileInputStream is used to read data from a file, one byte at a time.To create a FileInputStream object, you must pass the path to the file you want to read as a constructor argument. FileOutputStream is used to write data to a file, one byte at a time. It can be used to write any type of file, ...
๐ŸŒ
CodeJava
codejava.net โ€บ java-se โ€บ file-io โ€บ java-io-fileinputstream-and-fileoutputstream-examples
Java File IO FileInputStream and FileOutputStream Examples
[Master REST API Development and ... for manipulating binary files.In Java, FileInputStream and FileOutputStream are byte streams that read and write data in binary format, exactly 8-bit bytes....
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ what-is-the-use-of-fileinputstream-and-fileoutputstream-in-classes-in-java
Java - DataOutputStream Class
FileOutputStream creates a file (booleanData.dat). DataOutputStream.writeBoolean(true) writes 1 (one byte). DataOutputStream.writeBoolean(false) writes 0 (one byte). DataOutputStream.writeBoolean(true) writes 1 (one byte). The file now contains { 1, 0, 1 }. FileInputStream opens the file. DataInputStream.readBoolean() reads each byte and converts it to true (1) or false (0).
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ fileoutputstream in java
FileOutputStream in Java| Scaler Topics
January 11, 2024 - FileInputStream and FileOutputStream in Java are byte streams in the Java programming language that read and write data in binary format, which consists of exactly 8-bit bytes.
๐ŸŒ
W3Schools Blog
w3schools.blog โ€บ home โ€บ fileinputstream and fileoutputstream in java
FileInputStream and FileOutputStream in java - w3schools.blog
August 30, 2014 - FileInputStream fis = new ... = new IOTest(); //method call. obj.readFile(); } } Hello World. Download this example. FileOutputStream is used to create a file and write data into it....
๐ŸŒ
CodeGym
codegym.cc โ€บ java blog โ€บ java io & nio โ€บ input/output in java. fileinputstream, fileoutputstream, ...
Input/output in Java. FileInputStream, FileOutputStream, and BufferedInputStream classes
October 11, 2023 - There was a time when I spent hours ... forget to use the close() method to free resources. The FileInputStream has the opposite purpose โ€” reading bytes from a file. Just as FileOutputStream inherits OutputStream, this class ...
Find elsewhere
Top answer
1 of 2
6

1: Now I want to ask why writer use int c? even we are reading characters.

FileInputStream.read() returns one byte of data as an int. This works because a byte can be represented as an int without loss of precision. See this answer to understand why int is returned instead of byte.

2: The second why use -1 in while condition?

When the end of file is reached, -1 is returned.

3: How out.write(c); method convert int to again characters? that provide same output in outagain.txt file

FileOutputStream.write() takes a byte parameter as an int. Since an int spans over more values than a byte, the 24 high-order bits of the given int are ignored, making it a byte-compatible value: an int in Java is always 32 bits. By removing the 24 high-order bits, you're down to a 8 bits value, i.e. a byte.

I suggest you read carefully the Javadocs for each of those method. As reference, they answer all of your questions:

read:

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

write:

Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

2 of 2
1

Just read the docs.

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

public int read() throws IOException Reads a byte of data from this input stream. This method blocks if no input is yet available.

Specified by: read in class InputStream

Returns: the next byte of data, or -1 if the end of the file is reached.

That int is a your next set of bytes data. Now , here are the answers.

1) When you assign a char to an int, it denotes it's ascii number to the int.

If you are interested, here us the list of chars and their ascii codes https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

2)-1 if the end of the file is reached. So that's a check to data exists or not.

3)When you send an ascii code to print writer, it's prints that corresponding char to the file.

๐ŸŒ
Reintech
reintech.io โ€บ term โ€บ java-fileinputstream-fileoutputstream
Understanding FileInputStream and FileOutputStream in Java | Java Binary File Handling | Reintech media
Dive into FileInputStream and FileOutputStream classes in Java used for handling binary files. Understand how to read and write binary data.
Top answer
1 of 3
1

alter the loop condition to below:

while ((m = in.read()) != -1)
2 of 3
0

The problem with my code in an infinite loop of reading and writing. I can't find a solution or a concept for this problem.

There's a number of problems with your code:

  • The file will be treated as empty after the FileOutputStream gets instantiated because you've set append flag to false. End method read() will always return -1 because there's no content to read.

  • Condition is incorrect and method read() and only because of that control enters the loop and EOF (-1) is being repeatedly written into the file. If you fixed the condition to (m = in.read()) != -1, the loop would be ignored because the file is blank from the start.

  • If you would do both: fix the condition and change the append flag to true then you would get another flavor of infinite loop. All the contents of the file will be successfully read and repeatedly appended to the file.

So at any condition, reading and writing simultaneously to the same file isn't a good idea.

One important note in regard to exception handling.

Because there's no catch block in your code snippet, I assume that you've added a throws to the main() - it's not a nice idea. Methods close() in your code will be invoked only in case of successful execution, but if exception occur resources will never get released.

Instead, I suggest you to make use of try with resources. That will provide an implicit finally block for you that will take care of closing the resources regardless whether exception occurred or not (now your invocations of close() will not get executed in case of exception). Another option is to declare finally block explicitly, and close the resources inside it.

Try with resource is more concise and cleaner way to ensure that resources will get released.

Also consider wrapping both streams with buffered high-level streams to improve performance. It'll significantly reduce the number of time your application will need to access the file system.

    try (var in = new BufferedInputStream(new FileInputStream("source.txt"));
         var out = new BufferedOutputStream(new FileOutputStream("destination.txt", false))) {

        int next; // a subsequent byte that has been read from the source
        while ((next = in.read()) != -1) {
            out.write(next);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 8 โ€บ docs โ€บ api โ€บ java โ€บ io โ€บ FileInputStream.html
FileInputStream (Java Platform SE 8 )
April 21, 2026 - Javaโ„ข Platform Standard Ed. 8 ... A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ difference-between-inputstream-and-outputstream-in-java
Difference Between InputStream and OutputStream in Java - GeeksforGeeks
January 28, 2021 - // Imported to use inbuilt methods import java.io.FileOutputStream; // Main class public class OutputStreamExample { public static void main(String args[]) { // Writing in file gfg.txt try { FileOutputStream fileOut = new FileOutputStream("gfg.txt"); String s = "GeeksforGeeks"; // converting string into byte array byte b[] = s.getBytes(); fileOut.write(b); fileOut.close(); System.out.println( "file is successfully updated!!"); } catch (Exception e) { System.out.println(e); } } }
๐ŸŒ
CloudBees
cloudbees.com โ€บ blog โ€บ fileinputstream-fileoutputstream-considered-harmful
FileInputStream / FileOutputStream Considered Harmful
March 24, 2017 - For example, Hadoop found "long GC pauses were devoted to process high number of final references" resulting from the creation of lots of FileInputStream instances. The solution (at least if you are using Java 7 or newer) is not too hard - apart from retraining your muscle memory - just switch to Files.newInputStream(...) and Files.newOutputStream(...)
๐ŸŒ
Javatpoint
javatpoint.com โ€บ java-fileinputstream-class
Java FileInputStream Class
Constructor Constructor Description ... class which is used for file handling in java. Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string directly....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-io-fileinputstream-class-java
Java FileInputStream Class - GeeksforGeeks
November 3, 2025 - The FileInputStream class extends the InputStream class, which means it inherits methods for reading raw byte data from files. ... Example: FileInputStream class to read data from file.
๐ŸŒ
Studocu
studocu.com โ€บ tribhuvan vishwavidalaya โ€บ java programming โ€บ question
[Solved] 7 What are FileInputStream and FileOutputStream classes - Java Programming (CSc 409) - Studocu
June 4, 2024 - The FileInputStream and FileOutputStream classes in Java are used for reading and writing data from and to files, respectively.
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_fileinputstream.asp
Java FileInputStream
Note: The program also uses FileOutputStream. While FileInputStream is used to read bytes from a file, FileOutputStream is used to write bytes to a file. Together, they make it possible to copy any kind of file.
๐ŸŒ
Javatpoint
javatpoint.com โ€บ java-fileoutputstream-class
Java FileOutputStream Class - javatpoint
Java FileOutputStream Class for beginners and professionals with examples on Java IO or Input Output in Java with input stream, output stream, reader and writer class. The java.io package provides api to reading and writing data.