KeySi
KeySi

Reputation: 61

Java txt File from FileWriter is empty

I have trouble with write txt file from class FileWrite in my java project , if the PRINT() method were in VehicleCollection class , and called in main class - don't have problems. But I want print method be in different class which named FileWrite and called in main method from this class . Here peace of Code . I hope that i write correct question. if i should Explain more about my code I will .

I have 3 Classes 1st class is :

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...
    }
}

Second class is :

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);
            ...
        }

Third class is main class :

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

here Have error:cannot be applied to given types required ArrayList

Upvotes: 2

Views: 10748

Answers (2)

BillRobertson42
BillRobertson42

Reputation: 12883

File writes are usually buffered by the operating system. You must either close() or flush() the writer to make sure that the changes go to disk. If you're done with the file, just close it. A close will automatically flush the buffers.

Upvotes: 10

Hunter McMillen
Hunter McMillen

Reputation: 61510

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.

Upvotes: 3

Related Questions