当我尝试运行OUT.TXT
时,它始终为空。你能帮助我找出原因吗?另外SPY.LOG
行也不常见,你能帮助修复这些行吗?
package burak;
import java.io.*;
public class Yucal {
public static void main(String [] args) {
String fileName = "spy.log";
String line;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
try{
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(line);
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
System.out.printf("%65s\n", line);
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'"); }
}
答案 0 :(得分:2)
几乎没有变化
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
while ((line = bufferedReader.readLine()) != null) {
try {
out.write(line);
out.write("\n");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.printf("%65s\n", line);
}
out.close();
bufferedReader.close();
错误是你在while循环中打开了FileWriter fstream = new FileWriter("out.txt");
。它必须在外面。
答案 1 :(得分:1)
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
try{
>FileWriter fstream = new FileWriter("out.txt");**
>BufferedWriter out = new BufferedWriter(fstream);**
<snip>
每次打开文件并写一行。然后关闭它。下次打开它时,将覆盖文件的先前内容。您应该在while循环外移动标有&gt; 的行。
文件的最后一行 spy.log 可能为空。
答案 2 :(得分:0)
另外将所有关闭语句移动到finally块。
关闭这些流时,您可能还需要处理一些IO异常。
希望这有帮助。