FileWriter中的Java txt文件为空 [英] Java txt File from FileWriter is empty

查看:551
本文介绍了FileWriter中的Java txt文件为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 .

我有3个班级第一个班级是:

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

第二类是:

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

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

推荐答案

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

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.

这篇关于FileWriter中的Java txt文件为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆