我需要一些帮助,请将输出写入文件,但我无法让它工作。如果我使用 System.out.println 它就可以工作。如果我在实际方法中创建文件流和缓冲写入器,它会创建文件但不会向其中写入任何内容。我假设这是因为我的方法是递归的,并且每次该方法再次调用它自己时都会创建一个新文件。因此,我创建了另一个打印方法,并使用字符串值 key[i] 作为字符串参数,但它什么也不做。
感谢任何帮助,谢谢。
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
最佳答案
您需要关闭文件以确保内容被写入
关于java - 无法写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13790390/