在 servlet 中写入文件时出错
Error in wrting file in servlet
我已经通过 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.
@singhakash 提供的解决方案是正确的。
您可以使用
FileWriter fw=new FileWriter(filename,true);
并且如前所述,如果第二个参数为真,则将在末尾附加字节。
或者你可以使用getAbsoluteFile()
File的方法,这样
FileWriter fw=new FileWriter(filename.getAbsoluteFile());
The getAbsoluteFile()
method will return, The absolute abstract
pathname denoting the same file or directory as this abstract pathname(JavaDocs)
我已经通过 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.
@singhakash 提供的解决方案是正确的。
您可以使用
FileWriter fw=new FileWriter(filename,true);
并且如前所述,如果第二个参数为真,则将在末尾附加字节。
或者你可以使用getAbsoluteFile()
File的方法,这样
FileWriter fw=new FileWriter(filename.getAbsoluteFile());
The
getAbsoluteFile()
method will return, The absolute abstract pathname denoting the same file or directory as this abstract pathname(JavaDocs)