0

当我尝试运行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 + "'");           }
    }
4

3 回答 3

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

错误是你FileWriter fstream = new FileWriter("out.txt");在 while 循环中打开了。它必须在外面。

于 2013-07-16T13:57:14.563 回答
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 循环之外。

文件spy.log的最后一行可能为空。

于 2013-07-16T16:50:20.320 回答
0

另外将所有关闭语句移动到 finally 块。

当您关闭这些流时,您可能还需要处理一些 IO 异常。

希望这可以帮助。

于 2013-07-16T14:04:27.350 回答