如何在java中写入文件?

How to write file in java?

我面临文件写入问题,实际上当我 运行 下面的代码 while 循环迭代无限次。

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

谁能告诉我这个文件怎么写。

谢谢

斯坦苏

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

如果 c != -1,你认为这里会发生什么? 你不更新c的值,所以会造成死循环。

您只阅读了 c 一次。 将您的 while 循环更新为

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

此条件永远true保持为真,因为您永远不会在while-loop中更新c:

while (c != -1) {

使用in.read里面while-loop!

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

您错过了阅读下一个字节:

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

或者,您可以简单地使用:

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

尝试这样的事情:

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

就这样做

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