FileWriter中的Java txt文件为空

时间:2012-12-27 19:35:38

标签: java

如果PRINT()方法在VehicleCollection类中,并且在主类中调用,我在java项目中从类FileWrite写入txt文件时遇到问题 - 没有问题。但是我希望print方法在不同的类中,它命名为FileWrite,并在main类中调用此类。这里的代码和平。我希望我写出正确的问题。如果我应该更多地解释我的代码,我会。

我有3个课程,第一课是:

public class VehicleCollection  {

    private  ArrayList<VehicleInterface> arrList = new ArrayList<>();

    public ArrayList<VehicleInterface> getArrList() {
        return arrList;
    }

    void  setArrList(ArrayList<VehicleInterface> w){
        arrList = w;
    }

    public void getCollection() throws FileNotFoundException, IOException {
        Here Add in ArrayLIst...
    }
}

第二课是:

public class FileWrite extends VehicleCollection {

    FileWrite(ArrayList<VehicleInterface> w){
        setArrList(w);
    }

    public void print() throws FileNotFoundException {

        Writer writer = null;
        try {
            String text = getArrList().toString();
            File file = new File("krasiWrite.txt");
            writer = new BufferedWriter(new java.io.FileWriter(file));
            writer.write(text);
            ...
        }

第三课是主要课程:

FileWrite fw =  new FileWrite();
fw.print();

这里有错误:无法应用于给定类型所需的ArrayList

2 个答案:

答案 0 :(得分:6)

文件写入通常由操作系统缓冲。您必须close()flush()编写器以确保更改进入磁盘。如果您已完成该文件,请关闭它。关闭将自动刷新缓冲区。

答案 1 :(得分:2)

由于您已经在使用Java 7,为什么不使用try-with-resources结构来避免必须执行关闭流等操作:

try( File   file = new File("krasiWrite.txt"); 
     Writer writer = new BufferedWriter(new java.io.FileWriter(file)); )
{ 
     String text = getArrList().toString();
     writer.write(text);
     writer.flush(); // this lines takes whatever is stored in the BufferedWriter's internal buffer
                     // and writes it to the stream
}
catch(IOException ioe) {
   // ... handle exception
}

// now all resources are closed.