Good Evening, today i faced a strange situation when i used Print Writer in uploading files to a server, the file is transferred i tried to use FileOutPutStream instead and it solves the problem, my question is why PrintWriter does that strange behaviour, here’s the code that i used in uploading a file and save it at the server:
public void doPost(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
int i;
if(request instanceof MultipartWrapper){
String DestinationPath="C:\\";
MultipartWrapper request1=(MultipartWrapper)request;
File f=request1.getFile("photo");
java.io.FileInputStream fis=new java.io.FileInputStream(f);
//PrintWriter out=new PrintWriter(DestinationPath+f.getName()); causes the problem mentioned above
java.io.FileOutputStream out=new java.io.FileOutputStream(DestinationPath+f.getName());
while((i=fis.read())!=-1){
out.write(i);
}
fis.close();
out.close();
}
}
You need to understand the difference between Writers and OutputStreams.
PrintWriter.write(int)is writing a character, whileFileOutputStream.write(int)is writing a byte. you were accidentally converting bytes to characters, which was corrupting your file. in general, when just copying streams around, you want to stick to bytes.