【问题标题】:Why does the eclipse IDE give me terminated error when I try to write a file?为什么当我尝试写入文件时 Eclipse IDE 会出现终止错误?
【发布时间】:2012-06-14 14:22:01
【问题描述】:
import java.io.*;

public class FileWriterDemo {

/**
 * @param args
 */
public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

    String source = "Now is the time for all good men\n" +
                    " to come to aid of their country\n" +
                    " and pay their due taxes";

    char buffer[] = new char[source.length()];
    source.getChars(0, source.length(), buffer, 0);

    FileWriter f0 = new FileWriter("file1.txt");
    FileWriter f1 = new FileWriter("file2.txt");
    FileWriter f2 = new FileWriter("file3.txt");

    try{
        for(int i =0; i<buffer.length; i+=2){
            f0.write(buffer[i]);
        }

        f1.write(buffer);
        f2.write(buffer, buffer.length-buffer.length/4, buffer.length/4);

    }catch (IOException e){
        System.out.println("An I/O Error occured.");
    }
}

}

这是我编写的程序。我完全从一本书中复制了这个程序,但我的 IDE (Eclipse) 不断给我消息。当我尝试使用 FileOutputStream 类对象创建文件并写入文件时遇到了同样的问题。

这是一张图片

【问题讨论】:

  • 你确定这是一个错误而不是程序刚刚完成?
  • 您到底遇到了什么错误?此外,您可能希望在 catch 块中使用 e.printStackTrace 而不是 System.out.println(...)
  • 如果您要复制粘贴您看到的消息/错误,这将极大地帮助我们帮助您,我们不必猜测您的计算机上发生了什么。
  • 这不是一个错误,但我得到 .... 在我的控制台选项卡的标题中,没有任何输出。
  • 表示程序终止。从您的程序来看,如果成功终止,则不会打印任何内容。

标签: java eclipse file io


【解决方案1】:

这只是意味着程序已完成,在您的情况下可能成功,因为它没有在控制台上打印任何内容。

只要查看file1.txt , file2.txt and file3.txt的内容,看程序是否成功

【讨论】:

  • 我检查了每个文件。他们都神秘地空了
  • 尝试做 f0.flush(); f1.flush(); f2.flush();
  • 刷新实际上是将数据刷新到底层
  • 非常感谢。有效。你能解释一下这个机制吗?另外,如果我想在控制台输出文件,我应该创建 FileReader 对象吗?
  • 当您调用 write() 时,它只会将数据写入其缓冲区而不是文件。所以你需要调用 flush() 来强制写入底层文件系统。有一个例外,如果缓冲区被填满,它会自动刷新到文件中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-07
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多