我已经通过 servlet 中的 doPost 方法创建了一个文件,但无法向其中写入数据。我不明白是什么错误。顺便说一下,文件正在创建
// TODO Auto-generated method stub
response.setContentType("text/html");
String name=request.getParameter("name");
response.getWriter().println(name);
File filename= new File("/home/ksampath/D3/DedupeEngine/cache3.txt");
filename.createNewFile();
BufferedWriter out = null;
try
{
System.out.println("I am going to create a new file");
FileWriter fw=new FileWriter("cache3.txt",true);
out=new BufferedWriter(fw);
out.write("hello world");
out.write(name);
}
catch(IOException e)
{
System.err.println("Error"+ e.getMessage());
}
finally
{
if(out!=null)
{
out.close();
}
}
/*
System.out.println("Lets us check whether it works");
PrintWriter writer=response.getWriter();
writer.println("<h3>hello This is my first servlet</h3>");*/
}
最佳答案
尝试
FileWriter fw=new FileWriter(filename,true); //where filename is that File object
public FileWriter(File file, boolean append) throws IOException
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
关于java - 在servlet中写入文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28978944/