java - java中如何写入文件?

标签 java io inputstream outputstream

我面临文件写入问题,实际上当我运行下面的代码时,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();
                }
            }
        }
    }
}

任何人都可以告诉我如何编写这个文件。

谢谢

西坦苏

最佳答案

这个条件永远保持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();
}

关于java - java中如何写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30302803/

相关文章:

java - Joda-Time `DateTime` 对象到 `org.simpleframework.xml` ("Simple XML Serialization"库中字符串的转换器)

java - 如何从 Java 自动启动 Rserve?

Java io 句柄无效异常

c# - 捕捉 IOException

java - 在 Java 中将 InputStream 转换为字节数组

java - 使用可序列化接口(interface)可以进行选择性序列化吗?

java - 生成 UI 组件

c - C中如何进行就地计算

java - 为什么使用重定向的输入/输出流执行交互过程会导致应用程序停止?

java - 你如何决定 InputStream.read() 使用什么字节 [] 大小?