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