我正面临文件写入问题,实际上当我运行下面的代码时,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();
}
}
}
}
}
任何人都可以告诉我如何写这个文件。
由于
Sitansu
答案 0 :(得分:3)
此条件永久true
永久为真,因为您永远不会更新c
中的while-loop
:
while (c != -1) {
在 in.read
内使用while-loop
!
int c = in.read();
while (c != -1) {
System.out.println(c);
out.write(c);
c = in.read();
}
答案 1 :(得分:3)
您错过了阅读下一个字节:
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);
}
答案 2 :(得分:2)
您只能阅读c
一次。
将你的while循环更新为
while (c != -1) {
System.out.println(c);
out.write(c);
c = in.read();
}
答案 3 :(得分:1)
尝试这样的事情:
while(c != null){
System.out.println(c);
out.write(c);
c = reader.readLine();
}
答案 4 :(得分:1)
就这样做
toArray
答案 5 :(得分:0)
while (c != -1) {
System.out.println(c);
out.write(c);
}
如果c!= -1,你认为会发生什么? 你没有更新c的值,所以它会导致无限循环。