2

如果 PRINT() 方法在 VehicleCollection 类中并在主类中调用,我在 java 项目中从类 FileWrite 写入 txt 文件时遇到问题 - 没有问题。但我希望打印方法位于名为 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

4

2 回答 2

8

文件写入通常由操作系统缓冲。您必须要确保更改写入磁盘close()flush()如果您已完成该文件,只需将其关闭即可。关闭将自动刷新缓冲区。

于 2012-12-27T19:41:01.613 回答
3

Since you are already using Java 7, why not use the try-with-resources construct to avoid having to do things like close streams:

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.
于 2012-12-27T19:47:52.853 回答