我无法连续写入文件。我想要一个必须附加到该文件的函数。但是,我无法得到我需要的东西。如果编写的代码有任何错误,任何人都可以帮助我。
void writeLog(String s)
{
try
{
String filename= "D:\\Gardening\\Logs.txt";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write(s+"\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
大家,我在班级的构造函数中发现了问题,完整的代码在这里
Class Log
{
Log()
{
try{
FileWriter fw=new FileWriter("path of file");
}
catch(Exception a)
{
System.err.println(a);
}
}
void writeLog(String s)
{
try
{
String filename= "D:\\Gardening\\Logs.txt";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write(s+"\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
因为它在构造函数中被一次又一次地调用它发生了这样的事情。
答案 0 :(得分:1)
刚刚测试过你的代码,它运行正常。你能发布完整的代码吗?另外你如何调用writeLog方法。
public class Test {
void writeLog(String s) {
try {
String filename = "C:\\Temp\\Logs.txt";
FileWriter fw = new FileWriter(filename, true);
fw.write(s + "\n");
fw.close();
} catch (IOException ioe) {
System.err.println("IOException: " + ioe.getMessage());
}
}
public static void main(String[] args) {
Test t1 = new Test();
for (int i = 0; i < 5; i++) {
t1.writeLog("Hello");
}
}
}
此代码使用以下内容创建Logs.txt -
Hello
Hello
Hello
Hello
Hello
答案 1 :(得分:1)
尝试在您调用它的方法之外创建FileWriter,并将其作为第二个参数提供给您的方法。(如果您将字符串附加到整个项目中的文件,则可以将FileWriter创建为单例)无需一次又一次地重新创建FileWriter。
顺便说一下,你应该在finally块中关闭FileWriter。因为在您的代码中如果在关闭操作之前发生异常,则无法关闭FileWriter。我的代码建议如下:
public static void main(String[] args) {
FileWriter fw = null;
try {
fw = new FileWriter(filename,true);
writeLog("Your String", fw);
} catch (IOException ioe) {
System.err.println("IOException: " + ioe.getMessage());
}
finally
{
try {
if(fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static void writeLog(String s , FileWriter fw)
{
try
{
fw.write(s+"\n");
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}