Search code examples
javaioinputstreamoutputstream

How to write file in java?


I am facing file write issue ,Actually when i run this below code the while loop iterate infinite times.

package com.demo.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFile {

    public static void main(String[] args) {

        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream("C:/Users/s.swain/Desktop/loginissue.txt");
            out = new FileOutputStream("C:/Users/s.swain/Desktop/output.txt");
            int c = in.read();
            while (c != -1) {
                System.out.println(c);
                out.write(c);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Anyone can tell me how to write this file.

Thanks

Sitansu


Solution

  • This conditions remains true for eternity true because you never update c in the while-loop:

    while (c != -1) {
    

    Use in.read inside while-loop!

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