简体   繁体   中英

Can't Write to File

I need some help please writing the output to a file and I can't get it to work. If I use the System.out.println it works. If I create the file stream and Buffered Writer in the actual method, it creates the file but doesn't write anything to it. I'm assuming it's because my method is recursive and creates a new file every time the method calls it self again. So I created another print method and used the string value key[i] as the string parameter and it does nothing.

Any help is appreciated, thank you.

 public void print(String s)throws IOException
{
    fstream = new FileWriter("out.txt", true);
    out = new BufferedWriter(fstream);

    try{
        out.write("From print: " + s + " ");
        out.close();
    }catch (Exception e){//Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
}

public void generate() throws IOException
{ 
    while (k<randomWordNum())
    {
        if (randomNum() <= sumOfFreq[0])
        {
            //System.out.println(getKey[0] + " "); 
            print(getKey[i]);
            i++;
            k++;
            generate();
        }
        if (randomNum() >= sumOfFreq[i] && randomNum() <= sumOfFreq[i+1])
        {
            //System.out.println("From generate: " + getKey[i+1] + " "); 
            print(getKey[i+1]);
            i++;
            k++;
            generate();
        }
        else
        {
            i++;
            generate();
        }
    }//while
}//generate

您需要关闭文件以确保一切都写完

I think that constructor of FileWriter will overwrite the file. So you'll need to use a code line like this:

fstream = new FileWriter("out.txt", true); // true for appending

Also, always close a file before it goes out of scope, otherwise it might never get flushed or closed if you are unlucky...

And one more thing, assuming that is not some sort of debug/troubleshooting code, "never" catch Exception . If you do catch it, be sure to re-throw it asyou got it after logging or whatever you did with it. But, in general, always catch a more specific exception type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM