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 - This blog covers Java's FileInputStream and FileOutputStream classes, explaining how to read from and write to files using byte streams. It includes practical examples, key methods, and guidance on when to use these classes for efficient file handling.
🌐
CodeJava
codejava.net › java-se › file-io › java-io-fileinputstream-and-fileoutputstream-examples
Java File IO FileInputStream and FileOutputStream Examples
void close(): Closes this file output stream and releases any system resources associated with the stream.Almost methods throw IOException so remember to handle or declare to throw it in your code.Now, let’s see various code examples demonstrating the usages of the FileInputStream and FileOutputStream classes. ... import java.io.*; /** * This program demonstrates how to copy a file using the * FileInputStream and FileOutputStream classes with a * byte array as a buffer.
🌐
W3Schools
w3schools.com › java › java_fileinputstream.asp
Java FileInputStream
Here is an example that copies an image file: import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyFile { public static void main(String[] args) { // Copy image.jpg into copy.jpg try ...
🌐
W3Schools Blog
w3schools.blog › home › fileinputstream and fileoutputstream in java
FileInputStream and FileOutputStream in java - w3schools.blog
August 30, 2014 - FileOutputStream fos = new ... example. ... import java.io.FileInputStream; import java.io.FileOutputStream; /** * This program is used to read a file and write into another file....
🌐
Codespindle
codespindle.com › Java › Java_fileInputStream_fileoutputstream.html
FileInputStream and FileOutputStream in Java
If you set this parameter to true, FileOutputStream will append data to the end of the file instead of overwriting it. package javaprogrammingdemo; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; public class javalabclass{ public static void main(String args[]) throws IOException{ try { FileInputStream fs = new FileInputStream("satish.txt"); int data=fs.read(); System.out.print((char)data); fs.close(); } catch(FileNotFoundException e) { System.out.println("Check File"); } } }
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.

🌐
Scaler
scaler.com › home › topics › fileoutputstream in java
FileOutputStream in Java| Scaler Topics
January 11, 2024 - Say we have a text file c:/test.txt which will be used as input for our example program ... Then we should call the close() method to close the fout file. Let's discuss these methods of FileOutputStream to in detail to understand better · The FileOutputStream class provides implementations for different methods present in the OutputStream class ... We need to import the java.io package to use the FileOutputStream class.
Find elsewhere
🌐
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 - Today we'll consider 3 new classes: FileInputStream, FileOutputStream, and BufferedInputStream. The main purpose of the FileOutputStream class is to write bytes to a file. Nothing complicated :) FileOutputStream is one of the implementations of the OutputStream abstract class. In the constructor, objects of this class take either the path to the target file (where the bytes should be written) or a File object. We'll examine examples of each:
🌐
TutorialsPoint
tutorialspoint.com › what-is-the-use-of-fileinputstream-and-fileoutputstream-in-classes-in-java
Java - DataOutputStream Class
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class DataOutputStreamDemo { public static void main(String[] args) throws IOException { InputStream is = null; DataInputStream dis = null; FileOutputStream fos = null; DataOutputStream dos = null; String[] buf = {"Hello", "World!!"}; try { // create file output stream fos = new FileOutputStream("test.txt"); // create data output stream dos = new DataOutputStream(fos); // for each string in the buffer fo
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();
    }
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-io-input-output-in-java-with-examples
Input/Output in Java with Examples - GeeksforGeeks
import java.io.*; public class Geeks { public static void main( String[] args) throws IOException { FileInputStream sourceStream = null; FileOutputStream targetStream = null; try { sourceStream = new FileInputStream("sourcefile.txt"); targetStream = new FileOutputStream("targetfile.txt"); // Reading source file and writing content to target file byte by byte int temp; while (( temp = sourceStream.read()) != -1) targetStream.write((byte)temp); } finally { if (sourceStream != null) sourceStream.close(); if (targetStream != null) targetStream.close(); } } }
Published   December 10, 2025
🌐
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); } } }
🌐
Scientech Easy
scientecheasy.com › home › blog › fileoutputstream in java
FileOutputStream in Java - Scientech Easy
February 6, 2025 - Let’s create a program to copy data from one file to another file using FileInputStream and FileOutputStream classes. In the first file myfile.txt, we will store data as “Welcome to Scientech Easy”. Then, we will copy it and store it in ...
🌐
Javatpoint
javatpoint.com › java-fileinputstream-class
Java FileInputStream Class
Java FileInputStream 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.
🌐
Medium
medium.com › @dilipkumargurijala18 › mastering-file-i-o-in-java-working-with-inputstream-and-outputstream-6c6a968d0d72
Mastering File I/O in Java: Working with InputStream and OutputStream. | by DIlip Kumar Gurijala | Medium
January 26, 2025 - Purpose: Used for writing Java objects to an output stream in a serialized form. Use Case: Primarily used for object serialization (writing objects to a file or sending over the network).
🌐
Clemson University
people.computing.clemson.edu › ~yfeaste › cpsc215 › cpsc2150F15 › cpsc215Fall215 › Notes › Tutorialspoint_webpages › 18java_files_io.pdf pdf
Java - Files and I/O
Objects can be created using the keyword new · and there are several types of constructors available. Following constructor takes a file name as a string to create an input stream object to read the file.: InputStream f = new FileInputStream("C:/java/hello");
🌐
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 ...
🌐
W3Schools
w3schools.com › java › java_io_streams.asp
Java I/O Streams (Input/Output Streams)
Byte Streams Work with raw binary data (like images, audio, and PDF files). Examples: FileInputStream, FileOutputStream.