Sitansu
Sitansu

Reputation: 3329

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

Upvotes: 0

Views: 158

Answers (6)

tim
tim

Reputation: 467

Try something like this:

        while(c != null){
            System.out.println(c);
            out.write(c);
            c = reader.readLine();
        }     

Upvotes: 1

user2575725
user2575725

Reputation:

You missed to read the next byte:

int c = in.read();
while (c != -1) {
    System.out.println(c);
    out.write(c);
    c = in.read();//this line added to read next byte
}

Or, you can simply use:

int c;
while (-1 != (c = in.read())) { /* condition with assignment */
    out.write(c);
}

Upvotes: 3

Ajay Chaudhary
Ajay Chaudhary

Reputation: 308

Just do this

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

Upvotes: 1

Jordi Castilla
Jordi Castilla

Reputation: 26981

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

Upvotes: 3

QBrute
QBrute

Reputation: 4544

You only read c once. Update your while-loop to

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

Upvotes: 2

Stultuske
Stultuske

Reputation: 9437

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

what do you think will happen here, if c != -1 ? You don't update the value of c, so it will cause an infinite loop.

Upvotes: 0

Related Questions