BufferedInputStream / OutputStream Help

My File I/O program is up and running fine, but when I copy a text file to another location it adds a few more characters to the end of the file.
File fileF = new File( "H:\Java_Projects\db.rtf" );
File newFile = new File( H:"\Java_Projects\db2.rtf" );
//db2.rtf does not exist yet
BufferedInputStream bufIn = new BufferedInputStream( new FileInputStream( fileF ) );
BufferedOutputStream bufOut = new BufferedOutputStream ( new FileOutputStream( newFile ) );
int check;
byte [] buff = new byte[128];
while( ( check = bufIn.read( buff, 0, 128 ) ) != -1 ) {
bufOut.write( buff, 0, 128 );
bufOut.flush();
This code will copy any file type that you specify, but with long text files I get xtra characters at the very end.
Anybody know how to fix this? Thx!!

I'd replace this --
bufOut.write( buff, 0, 128 );with this --
bufOut.write( buff, 0, check );kind regards,
Jos

Similar Messages

  • InputStream / OutputStream Help

    I have in a series 10 commands to be executed on a server. so i am using Buffered OutputStream and DataOutputStream to write those commands to server.
    these commands have a set of protocol rule to be followed.
    for example i am creating a byte array and i am appending those protocol rules to the byte array and then finally to the stream and then writing to the socket of the server.
    everything works fine here.
    After that i must read the messages from the server.
    this is also fine but t�he problem is everytime i read different input for each command.
    i dont know why!!!!
    so my read function is as follows,
    import java.net.*;
    public class xxxxx
    InputStream instream;
    OutputStream outstream;
    public void OpenConnection() throws ConnectException,UnknownHostException
    try
         tcpipSocket = new Socket(tcpipparameters.getIpAddress(),tcpipparameters.getPortNumber());
    catch(IOException exception)
         System.out.println(exception.toString());
    try
         outstream = tcpipSocket.getOutputStream();
         instream = tcpipSocket.getInputStream();
         dos = new DataOutputStream(outstream);
         BufferedOutputStream bos= new BufferedOutputStream(dos);
         dis = new DataInputStream(instream);
         BufferedInputStream bis = new BufferedInputStream(dis);
    ////////// now i start the command execution on the server
    ///// The 1st Command --------------(The INIT Command)
         byte[] init = {0,6,0,2};
         init = createMessage.calculateCheckSum(init);
         int len = init.length;
         //dos.write(init,0,len);
         bos.write(init);
         bos.flush();
         int available;
         while((available = bis.available()) > 0)
              byte[] data = new byte[available];
              bis.read(data);
              for(int i = 0 ; i < data.length; i++)
                   System.out.print(data);
    ////////////////// The 2nd Command -------------------(IDENTIFY)
    byte[] identify = {0,16,0,20};
    // The protocol version number is inserted in to the IDENTIFY byte[]array
    int protocol_version_number = 512;
    byte[] protocol = {(byte)(protocol_version_number/256) ,(byte)(protocol_version_number%256) };
    byte[] temp = new byte[ identify.length +  protocol.length] ;
    System.arraycopy( identify, 0, temp, 0, identify.length ) ;
    System.arraycopy(protocol, 0, temp, identify.length, protocol.length ) ;
    identify = temp ;
    String PR_SName = "PRS2.0";
    identify = createString.stringData(identify,PR_SName);
    identify = createMessage.calculateCheckSum(identify);
    len = identify.length;
    bos.write(identify);
    bos.flush();
    int length1 = bis.available();
    System.out.println("length of the BufferedInputStream = " + length1);
    StringBuffer sb = new StringBuffer();
    for (int i=1; i<=length1; i++)
         char reply = (char)bis.read();
         sb.append(reply);
    System.out.println(sb.toString());
    ////////////////// The 3rd Command and So on................................
    catch(IOException exception)
         System.err.println("message = " + exception.getMessage());
    catch(InterruptedException e)
         System.err.println("Error =" + e);
    finally
         try
              //flush and close both "Instream" and "Outstream"
              dos.close();
              dis.close();
              instream.close();
              outstream.close();
         catch (IOException ex)
              ex.printStackTrace();
    every time the reading from the server is different.
    but i want to have the exact number of bytes to read everytime.
    so please correct me where i am wrong.
    With regards,
    Ashok
              public void CloseConnection()throws IOException
                        tcpipSocket.close();

    I would say the answer is in my previous replies to your question. I suggest you have another read of them.

  • Usage of BufferedInputStream & OutputStream#flush()

    I have a snippet below.
    InputStream fileInputStream = formFile.getInputStream();//org.apache.struts.upload.FormFile
    OutputStream out = = new BufferedOutputStream(new FileOutputStream(tempFilePath));
    byte[] buffer = new byte[256 * 1024];
    int contentLength;
    while ((contentLength = fileInputStream.read(buffer)) > 0) {
    out.write(buffer, 0, contentLength);
    out.close();
    fileInputStream.close();1. Should I use BufferedInputStream wrapping around formFile.getInputStream() ? I upload huge size files, say > 500 MB.
    2. Should I really call out.flush() somewhere ? If yes, should it be inside while loop or after while loop ?
    thanks in advance.

    baskark wrote:
    Otherwise, there's no need to call it. If you're already done writing, you'll call close(), and that will call flush() anyway. If you're writing all of the data in chunks one right after the other, and not stopping to do other processing between chunks, then you'll be writing as fast as possible and calling close() right away anyway, so, again, no benefit to calling flush.Will calling flush() before calling next write() make a difference in performance ?Calling flush unnecessarily could potentially slow things down, but you'd probably have to do a lot of it to be noticeable.
    Also using BufferedInputStream wrapping around formFile.getInputStream() improves performance in anyway ?If you're reading in large chunks with read(byte[]), it probably won't make a difference. But if you're reading into a very small byte array, or reading one byte at a time with read(), then using the BufferedInputStream will be baster.

  • Java OutputStream help

    Hello all,
    I am relatively new to using Java's Output and Input streams. I know the basics and I know how to use them but what is driving me crazy is I am not entirely sure how it works. For example I know the following code writes a file from an InputStream to an OutputStream:
    InputStream in = new FileInputStream(inputFile);
    OutputStream out = new FileOutputStream(outputFile);
    byte[] buffer = new byte[1024];
    int len;
    while((len = in.read(buffer))>0) {
        out.write(buffer, 0, len);
    }So if some one could be so kind as to explain a little about the following I would really appreciate it. (I don't know much about bytes)
    byte[] buffer = new byte[1024];
    Now I know this is an array of bytes but what role does this line of code play in writing to an OutputStream and why a size of 1024 and not 4000 or some other number?
    out.write(buffer, 0, len);
    I know under the java docs it says that len is the amount of bytes to write but isn't it just writing one byte at a time anyway? Lets say len had a value of one all the time, would that simply just write one byte at a time to the Output stream?
    out.write(byte[] b, int off, int len);
    Now under the java docs it explains that the byte array b is "the data" which I don't understand, is the OutputStream writing 1024 bytes to the byte array and then writing that byte array to the Output file? Why do I need a byte array in the first place?
    I know i'm asking a lot of questions but believe me I've tried to figure it out on my own. I've spent the last 4 hours trying to figure out how this code works by reading the java docs and looking it up on google etc but I can't seem to find a good tutorial or explanation for the questions I've asked. So thank you for reading this and thank you in advance for any input, its most appreciated.

    int[] sourceData = new int[1024]; // same as inputFile
    for(int i = 0; i < 1024; i++)
      sourceData[i] = (int)(Math.random() * 1024);
    int[] buffer = new int[1024];
    for(int i = 0; i < 1024; i++)
      buffer[i] = sourceData;
    int[] destinationData = new int[1024]; // same as outputFile
    for(int i = 0; i < 1024; i++)
    destinationData[i] = buffer[i];
    }If you can understand what this code is doing, then you got it--despite the fact that I'm using int[] instead of byte[].                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • When to use BufferedInputStream/OutputStream/Reader/Writer

    I'd be very grateful if someone could explain when to use BufferedInputStream, etc., and what the dis/advantages are.
    TIA
    Shaun

    data channels such as files sockets, etc, tend to be
    a) slow
    b) block oriented
    BufferedOutputStream attempts to mitigate this by presenting data in block format. Rather than a bunch of little segments of bytes.

  • Need help to download csv file in application by writting to outputstream.

    HI All,
    Requirment of my client is donloading CSV file from portal.
    My approach  is:
    On clicking "Download" button in JSP I am calling an action in controller and from here I am redirecting call to DownloadCSV.jsp where i am writing to output stream of response.
    Action called in controller:
         @Jpf.Action(forwards = { @Jpf.Forward(name = StaticConstants.SUCCESS, redirect = true, path = "DownloadCSV.jsp") })
         public Forward gotoReports() {
              Forward forward = new Forward(StaticConstants.SUCCESS);
              return forward;
    Download jsp:
    response.resetBuffer();
         response.reset();
         response.setContentType("application/vnd.ms-excel");
         response.addHeader("Content-Disposition", "attachment;filename="+ companyId +"_Audit_Report.csv");
         ServletOutputStream os = response.getOutputStream();
              os .println();
              os .print("DATE");
              os .print("USER");
    os .println();
    os.flush();
    os.close();
    I am able to download the csv file in excel. But after that i am not able to perform any operation in portal page. Mouser pointer becomes busy and cant click on anything.
    Second approach followed:
    I wrote the code for writting to outputstream of outputresponse in controller action itself and forwarded to the same jsp where my download button resides.
    Problem:
    Download happens perfectly but the excel in csv format contains the portal framework generated content also other than content i wrote to response.
    If u have any other approach to download an excel without redirecting to JSP plz let me know. Coing is being done in 10.2 weblogic portal.
    Please help. Its very urgent.
    Plz let me know how a file can be downloded in portal context without keeping a file at server side. I need to download file by writting to outputstream.
    If it is possible plz attach one small example project also.
    Thanks a ton in advance.
    It is very important plz do reply.

    Hi Srinivas,
    For downloading binary content that is not text/html, the Oracle WebLogic Portal content management tools use javascript in an onclick event handler to set the window URL to the URL of a download pageflow controller: window.location = url. The content management tools are in a portal so it should be possible for you to do the same thing.
    The url is a custom pageflow controller that streams the bytes to the response. It sounds like you already have a pageflow you could recycle to use in that way. You don't want to stay within your portlet pageflow because then you will be streaming bytes into the middle of a portal response. You want a separate download pageflow that you invoke directly, outside of the portal framework (in other words, don't invoke it by rendering a portlet that invokes the pageflow).
    You can set the url to invoke the pageflow directly by giving the path to the pageflow controller from the web root (remember the pageflow path matches the package name of the pageflow controller class) like this: "/content/node/nodeSelected/download/DownloadContentController.jpf"
    By the way, for the case of text/html, the tools uses a standalone portlet URL so that the text/html is not rendered in the browser window, which would replace the portal markup (because the browser renders text/html by default, instead of giving you a download widget or opening some other application to deal with the bytes).

  • HELP..Using BufferedInputStream

    Hi I am trying to send a video file (.mpg) from a tcp server written in C to a tcp client written in Java. The server seems to be sending the bytes accurately. But on the JAva client end, the bytes are recived but each time the numbers of bytes recived are different and when I compare the file produced in Java it has some missing bytes, some repeated bytes and some delayed bytes. I have been trying for 2 weeks, with all different combination of streams (Buffered, Object, Data). From the C porgram I am sending bytes using (char*) so I assumed I would have to receive bytes, so I used BufferedInputStream...but it didn't work.....
    the following is the code i used to recive the mpg file.
    File file = new File("C:/outfilename106.mpg);
    file.createNewFile();
    FileOutputStream fout=new FileOutputStream(file);
    BufferedOutputStream out2=new BufferedOutputStream(fout);
    BufferedInputStream in2=new BufferedInputStream(socket.getInputStream());
    while(in2.read(buffer)!=-1)
              out2.write(buffer);
    it seems perhaps i am using teh wrong streams to receive video file, or the wrong way to write to a file?????or something else
    Please help!!..i have been tryimg for long..i have a project due very soon..and because of this nothing will work..thanks.....

    while(in2.read(buffer)!=-1)
              out2.write(buffer);
    int count;
    while ((count = in2.read(buffer)) != -1)
        out2.write(buffer,0,count);
    }This would be just about #1 in the FAQ if there was one.

  • Need help with applet servlet communication .. not able to get OutputStream

    i am facing problem with applet and servlet communication. i need to send few image files from my applet to the servlet to save those images in DB.
    i need help with sending image data to my servlet.
    below is my sample program which i am trying.
    java source code which i am using in my applet ..
    public class Test {
        public static void main(String argv[]) {
            try {
                    URL serverURL = new URL("http://localhost:8084/uploadApp/TestServlet");
                    URLConnection connection = serverURL.openConnection();
                    Intermediate value=new Intermediate();
                    value.setUserId("user123");
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setUseCaches(false);
                    connection.setDefaultUseCaches(false);
                    // Specify the content type that we will send binary data
                    connection.setRequestProperty ("Content-Type", "application/octet-stream");
                    ObjectOutputStream outputStream = new ObjectOutputStream(connection.getOutputStream());
                    outputStream.writeObject(value);
                    outputStream.flush();
                    outputStream.close();
                } catch (MalformedURLException ex) {
                    System.out.println(ex.getMessage());
                }  catch (IOException ex) {
                        System.out.println(ex.getMessage());
    }servlet code here ..
    public class TestServlet extends HttpServlet {
         * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
             System.out.println(" in servlet -----------");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            ObjectInputStream inputFromApplet = null;
            Intermediate aStudent = null;
            BufferedReader inTest = null;
            try {         
                // get an input stream from the applet
                inputFromApplet = new ObjectInputStream(request.getInputStream());
                // read the serialized object data from applet
                data = (Intermediate) inputFromApplet.readObject();
                System.out.println("userid in servlet -----------"+ data.getUserId());
                inputFromApplet.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("WARNING! filename.path JNDI not found");
            } finally {
                out.close();
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println(" in foGet -----------");
            processRequest(request, response);
         * Handles the HTTP <code>POST</code> method.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println(" in doPost -----------");
            processRequest(request, response);
         * Returns a short description of the servlet.
         * @return a String containing servlet description
        @Override
        public String getServletInfo() {
            return "Short description";
        }// </editor-fold>
    }the Intermediate class ..
    import java.io.Serializable;
    public class Intermediate implements Serializable{
    String userId;
        public String getUserId() {
            return userId;
        public void setUserId(String userId) {
            this.userId = userId;
    }

    Hi,
    well i am not able to get any value from connection.getOutputStream() and i doubt my applet is not able to hit the servlet. could you review my code and tell me if it has some bug somewhere. and more over i want to know how to send multiple file data from applet to servlet . i want some sample or example if possible.
    do share if you have any experience of this sort..
    Thanks.

  • Help while writing to OutputStream

    Hello All,
    I have to write FileInputStream to the OutputStream but it shud not be in character wise writing but I have to write the file atleast in a chunk of say 4096 bytes.
    Anybody with a solution ?.
    Thanks and regards,
    Sachin

    Hey I am providing the code.
    File file = new File(path);
    OutputStream os = con.getOutputStream();
    ;               FileInputStream fis = new
    FileInputStream(file);
         int newData = 0;
         int len= (int)file.length();
         byte[] b = new byte[len];
         int c =0;
         while((c = fis.read(b))>0){
         os.write(c);
    This is the code but when I try to write a file
    having the size of say 10 MB it writes only 100 KB
    not more .Can anybody tell me why ?.
    Thanks and regards,
    SachinI already told you. You want to write bytes from your "b" array, not your "c" variable (which only has the number of bytes read). The bytes you read are in your "b" array. Are you listening? Hello? Echo?

  • OutputStream + Browser.......Help!!! Urgent.Please.

    Hi,
    I need to finish this browser project ASAP....
    Let me tell you what my situation is...
    I am getting a Tiff image from DB and converting to JPEG in OutputStream....
    I want to dispaly the OutputStream on a Browser....
    Is there a way to do this or is there any other way i can do this....
    If anyone can show me a simple example, i would greatly appreciate it...
    Again Thanks.

    Well if your website root (IE "your.site.com/") was mapped to your C drive, the html would be <img src="sample1.jpg" />.
    Is that what you are asking? I'm guessing by your first question that this isn't what you are asking. I'm guessing you want to dynamically create an image and serve it to the user, right?
    If that is the case see my first post and the API for OutputStream.

  • Sending a file from Applet to servlet HELP me Please

    Sorry, i have the problem this is my code Applet & Servlet but it seems working asynchronously if you have some ideas please reply me i send bytes on outputstream but the inputstream of servlet receive nothing bytes but write my system.out.print on screen server:
    Applet:
    URL servletURL = new URL(codebase, "/InviaFile/servlet/Ricevi");
    HttpURLConnection urlConnection = (HttpURLConnection) servletURL.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    urlConnection.setRequestProperty("Content-length", String.valueOf(100));
    urlConnection.connect();
    if(urlConnection.HTTP_BAD_REQUEST == HttpURLConnection.HTTP_BAD_REQUEST){
    /*System.out.println("Cattiva Richiesta: "+urlConnection.getContentEncoding());
    System.out.println("Tipo di metodo: "+urlConnection.getRequestMethod());
    System.out.println("Tipo di Risposta: "+urlConnection.getResponseCode());
    System.out.println("Tipo di messaggio: "+urlConnection.getResponseMessage());
    System.out.println("Tipo di contenuto: "+urlConnection.getContentType());
    System.out.println("Tipo di lunghezza contenuto: "+urlConnection.getContentLength());
    System.out.println("Tipo di doinput: "+urlConnection.getDoInput());
    System.out.println("Tipo di doouput: "+urlConnection.getDoOutput());
    System.out.println("Tipo di URL: "+urlConnection.getURL());
    System.out.println("Tipo di propriet� richiesta: "+urlConnection.getRequestProperty("Content-Type"));
    System.out.println("Entra if");
    DataOutputStream dout = new DataOutputStream(urlConnection.getOutputStream());
    InputStream is = urlConnection.getInputStream();
    if(ritornaFile("C:/Ms.tif", dout))System.out.println("Finita lettura");
    dout.close();
    urlConnection.disconnect();
    System.out.println("Fine Applet");
    }catch(Exception e) { System.err.println(e.getMessage());e.printStackTrace();}
    public boolean ritornaFile(String file, OutputStream ots)throws Exception{
    FileInputStream f = null;
    try{
    f = new FileInputStream(file);
    byte[] buf = new byte[4 * 1024];
    int byteLetti;
    while((byteLetti = f.read()) != -1){ots.writeByte(buf, 0, byteLetti);ots.flush();
    while((byteLetti = f.read()) != -1){ots.write(byteLetti);ots.flush();
    System.out.println("byteLetti= "+byteLetti);
    return true;
    }catch(Exception ex){
    System.err.println(ex.getMessage());
    return false;
    }finally{
    if(f != null)f.close();
    Servlet:
    HttpSession ses = request.getSession(true);
    System.out.println("Passa servlet "+request.getMethod());
    System.out.println("Passa servlet "+ses.getId());
    ServletInputStream servletinputstream = request.getInputStream();
    DataInputStream dis = new DataInputStream(request.getInputStream());
    int c = dis.available();
    System.out.println("c="+c);
    //ServletOutputStream servletoutputstream
    //response.getOutputStream();
    response.setContentType("application/octet-stream");
    System.out.println("URI= "+request.getRequestURI());
    System.out.println("pathTranslated: "+request.getPathTranslated());
    System.out.println("RemoteUser: "+request.getRemoteUser());
    System.out.println("UserInRole: "+String.valueOf(request.isUserInRole("")));
    System.out.println("pathInfo: "+request.getPathInfo());
    System.out.println("Protocollo: "+request.getProtocol());
    System.out.println("RemoteAddr:"+request.getRemoteAddr());
    System.out.println("RemoteHost:"+request.getRemoteHost());
    System.out.println("SessionID:"+request.getRequestedSessionId());
    System.out.println("Schema:"+request.getScheme());
    System.out.println("SeesionValido:"+String.valueOf(request.isRequestedSessionIdValid()));
    System.out.println("FromURL:"+String.valueOf(request.isRequestedSessionIdFromURL()));
    int i = request.getContentLength();
    System.out.println("i: "+i);
    ritornaFile(servletinputstream, "C:"+File.separator+"Pluto.tif");
    System.out.println("GetMimeType= "+getServletContext().getMimeType("Ms.tif"));
    InputStream is = request.getInputStream();
    int in = is.available();
    System.out.println("Legge dallo stream in="+in);
    DataInputStream diss = new DataInputStream(servletinputstream);
    int ins = diss.read();
    System.out.println("Legge dallo stream ins="+ins);
    int disins = diss.available();
    System.out.println("Legge dallo stream disins="+disins);
    is.close();
    System.out.println("Fine Servlet");
    catch(Exception exception) {
    System.out.println("IOException occured in the Server: " + exception.getMessage());exception.printStackTrace();
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    /** Returns a short description of the servlet.
    public String getServletInfo() {
    return "Short description";
    public void ritornaFile(InputStream its, String fileDest )throws Exception{
    FileOutputStream f = null;
    try{
    f = new FileOutputStream(fileDest);
    byte[] buf = new byte[2 * 1024];
    int byteLetti;
    while((byteLetti = its.read()) != -1){
    f.write(buf, 0, byteLetti);
    f.flush();
    System.out.println("Byteletti="+byteLetti);
    }catch(Exception ex){
    System.err.println(ex.getMessage());
    }finally{
    if(f != null)f.close();

    Hi all,
    Can anyone help me.I am trying to send an audio file from a applet to servlet with HTTP method(no raw sockets), also the servlet shld be able to save the file on the server.Any suggestions welcome.USing audiostream class from javax.sound.sampled.
    The part of applet code which calls servlet is :
    URL url = new URL("http://" + host + "/" + context + "/servlet/UserUpdateWorkLogAudio?userid=" + userId.replace(' ', '+') + "&FileName=" + filename.replace(' ', '+'));
    URLConnection myConnection = url.openConnection();
    myConnection.setUseCaches(false);
    myConnection.setDoOutput(true);
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    myConnection.connect();
    out = new BufferedOutputStream(myConnection.getOutputStream());
    AudioSystem.write(audioInputStream, fileType,out); // IS THIS RIGHT APPROACH?
    ************************end of applet code**********************
    ************************servlet code******************************
    try
    {BufferedInputStream in = new BufferedInputStream(request.getInputStream());
    ????????What code shld i write here to get the audio file stream
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
    *********************************************end***********************
    Thanks
    Joe.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Please help me with the error of Java related to UNIX

    Can you help me with my code?
    I wrote a Java program and ran it in gdb, the debugger said that :
    (gdb) run handhelditems 1 1000
    Starting program: /home/wqq/crawl/handhelditems/crawl_what_i_want handhelditems 1 1000
    [Thread debugging using libthread_db enabled]
    [New Thread -1208232256 (LWP 3796)]
    [New Thread -1210332272 (LWP 3799)]
    [New Thread -1220822128 (LWP 3800)]
    [New Thread -1231311984 (LWP 3801)]
    [New Thread -1243206768 (LWP 3802)]
    [New Thread -1253696624 (LWP 3803)]
    [New Thread -1264186480 (LWP 3804)]
    [New Thread -1274676336 (LWP 3805)]
    [New Thread -1285166192 (LWP 3806)]
    [New Thread -1295656048 (LWP 3807)]
    [New Thread -1306145904 (LWP 3808)]
    [New Thread -1316635760 (LWP 3809)]
    Program received signal SIGPWR, Power fail/restart.
    [Switching to Thread -1316635760 (LWP 3809)]
    0x00196402 in __kernel_vsyscall ()
    (gdb)
    the crawl_what_i_want.java is :
    public class crawl_what_i_want {
         public static void main(String[] args){
              if(args.length!=3){
                   System.out.println("Usage: java crawl_html [site name] [start at] [end at]");
              else
                   String v1 = args[0];
                   int v2 = Integer.parseInt(args[1]);
                   int v3 = Integer.parseInt(args[2]);
                   thread thread0 = new thread(v1,v2,v3,0);
                   thread thread1 = new thread(v1,v2,v3,1);
                   thread thread2 = new thread(v1,v2,v3,2);
                   thread thread3 = new thread(v1,v2,v3,3);
                   thread thread4 = new thread(v1,v2,v3,4);
                   thread thread5 = new thread(v1,v2,v3,5);
                   thread thread6 = new thread(v1,v2,v3,6);
                   thread thread7 = new thread(v1,v2,v3,7);
                   thread thread8 = new thread(v1,v2,v3,8);
                   thread thread9 = new thread(v1,v2,v3,9);
                   thread0.start();
                   thread1.start();
                   thread2.start();
                   thread3.start();
                   thread4.start();
                   thread5.start();
                   thread6.start();
                   thread7.start();
                   thread8.start();
                   thread9.start();
    the thread.java is :
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import java.net.*;
    public class thread extends Thread
         String site_n;
         int s_at;
         int e_at;
         int for_id;
         thread(String site_n,int s_at,int e_at,int for_id){
              this.site_n = site_n;
              this.s_at = s_at;
              this.e_at = e_at;
              this.for_id = for_id;
         public synchronized void run() {
              String site = site_n;
              int fornum = for_id;
              int start = s_at;
              int end = e_at;
              //String site_name = "http://www."+site+".com";
              ArrayList url_list = new ArrayList();
              ArrayList url_id_list = new ArrayList();
              try{
                   Class.forName("com.mysql.jdbc.Driver").newInstance();
                   String getconn = "jdbc:mysql://localhost/url_set_"+site+"?user=xxxx&password=xxxx";
                   Connection conn = DriverManager.getConnection(getconn);
                   PreparedStatement stmt = conn.prepareStatement("");
                   ResultSet rs = null;
                   stmt = conn.prepareStatement("select url,url_id from urls where url_id>=? and url_id<=?");
                   stmt.setInt(1,start);
                   stmt.setInt(2,end);
                   rs = stmt.executeQuery();
                   while(rs.next())
                        url_id_list.add(rs.getString(2));
                        url_list.add(rs.getString(1));
                   if(rs!=null)
                        rs.close();
                   stmt.close();
                   conn.close();
              catch(Exception e){
                   e.printStackTrace();
              try{
                   InputStream in = null;
                   InputStreamReader rd = null;
                   BufferedReader br = null;
                   for(int i=fornum; i<url_list.size(); i=i+10){
                        String save_dir = "./" + String.valueOf(Integer.parseInt(url_id_list.get(i).toString())/10000) + "/" ;
                        try{
                             if(!(new File(save_dir).isDirectory()))
                                  new File(save_dir).mkdir();
                        catch(Exception exp){
                             exp.printStackTrace();
                        String html = "";
                        URL this_url = new URL(url_list.get(i).toString());
                    in = this_url.openConnection().getInputStream();
                    rd = new InputStreamReader(in);
                    br=new BufferedReader(rd);
                    String line = br.readLine();
                    int imgmark = 0 ;
                    while(line != null){
                        html += line + (char)13;
                        //  get image  //
                        if(line.indexOf("product image(s) bof")>0)
                             imgmark = 1;
                        if(line.indexOf("product image(s) eof")>0)
                             imgmark = 0;
                        if(imgmark == 1 && line.indexOf("img src")>=0)
                             int bofimg = line.indexOf("http://www.unix.com/images/");
                             int eofimg = line.indexOf("jpg\"")+3;
                             if(eofimg>bofimg){
                                   String imgURL = "http://www."+site+".com/" + line.substring(bofimg,eofimg);
                                   String imgdir = save_dir + url_id_list.get(i).toString() + ".jpg";
                                   getpic gp = new getpic();
                                   gp.crawlpic(imgURL,imgdir);
                        line = br.readLine();
                     br.close();
                     rd.close();
                     in.close();
                        if(html==null)
                             html = "";
                        if(html.length()>0){
                             String saveTo = save_dir+ url_id_list.get(i).toString() +".html";
                             try {
                                  new outPut(html, saveTo);
                             } catch (IOException e) {
                                  e.printStackTrace();
                             System.out.println((i+start) + ". Saved " + url_list.get(i) + " as " + (i+start) + ".html");
                        else
                             System.out.println((i+start) + ". failed at " + url_list.get(i));
                   if(br!=null)
                        br.close();
              }catch (Exception e){
                   e.printStackTrace();
    the outPut.java is :
    import java.io.*;
    public class outPut {
            public outPut(String content, String outPutFile)throws IOException{
                    FileWriter fl = null;
                    BufferedWriter bw = null;
                    try{
                            File f = new File(outPutFile);
                            if(!f.exists())
                                    f.createNewFile();
                            fl = new FileWriter(outPutFile);
                            bw = new BufferedWriter(fl);
                            bw.write(content);
                    finally{
                            if(bw!=null)
                                    bw.flush();
                            if(fl!=null)
                                    fl.flush();
                            if(bw!=null)
                                    bw.close();
                            if(fl!=null)
                                    fl.close();
    the getpic.java is
    import java.io.*;
    import java.net.*;
    public class getpic {
            public synchronized void crawlpic(String url, String savedir)throws Exception {
                InputStream in = null;
                InputStream inBuffer = null;
                OutputStream out = null;           
                try{
                    URL this_url = new URL(url);
                    in = this_url.openConnection().getInputStream();
                        inBuffer = new BufferedInputStream(in);
                        out = new FileOutputStream(savedir);
                        while(true){
                        int bytedata = inBuffer.read();
                        if(bytedata == -1)
                        break;
                        out.write(bytedata);
                finally{
                    if(out != null)
                            out.close();
                    if(inBuffer != null)
                            inBuffer.close();
                    if(in != null)
                            in.close();
    }above are all my code .
    On the other hand, the codes can be run at JDB, but it will lose some thread after run for some minute or seconds.

    Hi aarthi,
    SELECT can be used to fetch data only from database tables/views. in your case you used SELECT from an INTERNAL table,which is not allowed.
    SELECT  *
           FROM <DBTABLE NAME>
           INTO TABLE EXPORT_REC
           WHERE KEY = IMPORT_ PARAMETER AND   
           IMPORT_PARAM_DATE BETWEEN FROM_DATE AND TO_DATE.
    HERE Instead of <DBTABLE NAME>,you have to give your Database table,which stores these values.
    then your data will comes into EXPORT_REC.
    and remember to give EXPORT_REC in TABLES parameters of that FUNCTION MODULE and give associated Type for that.
    Regards
    Srikanth

  • Help needed very urgent

    I have problem in downloading a file through a servlet. Let me put my points clearly.
    When a client requests my servlet using setcontenttype, setheader methods I prompt for the 'save' option.
    The client can choose the file and save in his local directory.
    The problem now is, if he cancels in between or at the initial stage itself an exception saying 'connection reset by peer' should be thrown at the server side.
    When I execute the servlet in javawebserver2.0/weblogic 5.0, the exception is thrown.
    Whereas when I use the same servlet in weblogic6.0sp1win no exception is thrown.
    I want the exception to be thrown even in weblogic6.0sp1win.
    How to overcome this problem. Please help me out at the earliest.
    Please see the code below.
    I am eagerly awaiting for your feedback. I have posted this query several times in java and jguru forum but did not get any reply till now.
    Since the problem is very serious please help me out as soon as possible. thanks
    luv,
    venkat.
    //code
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.security.*;
    public class TestServ extends HttpServlet //implements javax.jms.Connection
    Exception exception;
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException, UnavailableException
         int bytesRead=0;
         int count=0;
         byte[] buff=new byte[1];
    OutputStream out=res.getOutputStream ();
    // Set the output data's mime type
    res.setContentType( "application/pdf");//application/pdf" ); // MIME type for pdf doc
    // create an input stream from fileURL
    String fileURL ="http://localhost:7001/soap.pdf";
    // Content-disposition header - don't open in browser and
    // set the "Save As..." filename.
    // *There is reportedly a bug in IE4.0 which ignores this...
    // PROXY_HOST and PROXY_PORT should be your proxy host and port
    // that will let you go through the firewall without authentication.
    // Otherwise set the system properties and use URLConnection.getInputStream().
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    boolean download=false;
         res.setHeader("Content-disposition", "attachment; filename="+"xml.pdf" );
    try
              URL url=new URL(fileURL);
         bis = new BufferedInputStream(url.openStream());
         bos = new BufferedOutputStream(out);
    while(-1 != (bytesRead = bis.read(buff, 0, buff.length)))
              try
                   bos.write(bytesRead);
                   bos.flush();
                   }//end of try for while loop
                   catch(SocketException e)
                        setError(e);
                        break;
                   catch(Exception e)
                        System.out.println("Exception in while of TestServlet is " +e.getMessage());
                        if(e != null)
                             System.out.println("File not downloaded properly");
                             setError(e);
                             break;
                        }//if ends
                   }//end of catch for while loop
    }//while ends
              Exception eError=getError();
              if(eError!=null)
                   System.out.println("\n\n\n\nFile Not DownLoaded properly\n\n\n\n");
              else if(bytesRead == -1)
              System.out.println("\n\n\n\ndownload successful\n\n\n\n");
              else
              System.out.println("\n\n\n\ndownload not successful\n\n\n\n");
    catch(MalformedURLException e)
    System.out.println ( "Exception inside TestServlet is " +e.getMessage());
    catch(IOException e)
    System.out.println ( "IOException inside TestServlet is " +e.getMessage());
         finally {
              try
    if (bis != null)
    bis.close();
    if (bos != null)
    bos.close();
              catch(Exception e)
                   System.out.println("here ="+e);
    }//doPost ends
         public void setError(Exception e)
              exception=e;
              System.out.println("\n\n\nException occurred is "+e+"\n\n\n");
         public Exception getError()
                   return exception;
    }//class ends

    My idea is:
    When user cancel the operation, browser send a message back but webserver/weblogic just ingnores it.
    You check BufferOutputStream class or any other class that it extends to see if flush() method does really flushed, if not then it means that the operation has been cancelled.

  • Help with error (apache tomcat + java )

    hi all ! Im having an issue with my program.
    Im using jasper report to generate some reports from the program... everything seems to work except for this (making the program unstable at some point). When the report is generated and loaded as a pdf I get this error in the log.
    java.lang.IllegalStateException
    at org.apache.coyote.Response.reset(Response.java:296)
    at org.apache.catalina.connector.Response.reset(Response.java:642)
    at org.apache.catalina.connector.Response.reset(Response.java:908)
    at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:355)
    at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:211)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:134)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:825)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:736)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:526)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
    at java.lang.Thread.run(Thread.java:619)
    The code Im using to generate the pdf is this one.
    File file = new File("C:\\Reportes\\", reporte +""+ datNac +".pdf");
    String contentType = getServletContext().getMimeType(reporte+ "" +datNac+ ".pdf");
    System.out.println("antes BufferedOutputStream");
    BufferedOutputStream output = null;
    output = new BufferedOutputStream(response.getOutputStream());
    BufferedInputStream inputFile = null;
    inputFile = new BufferedInputStream(new FileInputStream(file));
    response.reset();
    response.setContentType(contentType);
    response.setContentLength((int) file.length());
    response.setHeader("Content-disposition",
    "attachment; filename=\"" +file.getName()+ "\"");
    System.out.println("BufferedOutputStream");
    byte[] buffer = new byte[10240];
    for (int length; (length = inputFile.read(buffer)) != -1;) {
    output.write(buffer, 0, length);
    inputFile.close();
    output.close();Any help is appreciated.
    Thanks!
    Edited by: juanmanuelsanchez on Aug 4, 2009 11:17 AM
    Edited by: juanmanuelsanchez on Aug 4, 2009 11:18 AM
    Edited by: juanmanuelsanchez on Aug 4, 2009 11:19 AM

    juanmanuelsanchez wrote:
    java.lang.IllegalStateException
    at org.apache.coyote.Response.reset(Response.java:296)The response is already committed and thus cannot be reset anymore.
    output = new BufferedOutputStream(response.getOutputStream());
    response.reset();At least you should obtain the outputstream AFTER the reset. If that doesn't fix, then check everything in the chain before this code.

  • Sockets in rmi, help needed

    hi,
    I need a help on using sockets in rmi for communication between the server and the client. I am trying to establish a communication between the server and client through sockets after the remote method call is invoked but before it is fulfilled. I my code the socket is not establishing in the client side. Do help me out at the earliest pls... thanks in advance..

    I am trying to use sockets inside a rmi. Still i have the problem. I cant get my client listen from the server.
    First the client invokes a remote object. Before server sending the actual request of the requested by the remote object i want to make some communication between the server and client through sockets.
    I created a ServerSocket in the client side. The problem I have is the ServerSocket is not listening to the server request.
    Here i ve my code.I cant figure out what mistake i have done. It also dont show any error. As i am new to RMI and sockets i am in need of help. So pls do help me... Thanks in advance.
    In my example i am trying to verify the password before the server downloads the file for the client. So i want the verification done through sockets and download file using RMI.
    FileInterface.java
    import java.rmi.*;
    public interface FileInterface extends Remote
    public byte[] downloadFile(String fileName) throws RemoteException;
    FileServer.java
    import java.rmi.*;
    import java.io.*;
    public class FileServer
    public static void main(String []args)
      if(System.getSecurityManager()==null)
       System.setSecurityManager(new RMISecurityManager());
      try
       FileImpl fi=new FileImpl("FileServer");
       Naming.rebind("FileServer",fi);
         System.out.println("Server bound"+fi);
      catch(Exception e)
       System.out.println("FileServer: "+e.getMessage());
    FileImpl.java
    import java.io.*;
    import java.net.*;
    import java.rmi.*;
    import java.rmi.server.UnicastRemoteObject;
    public class FileImpl extends UnicastRemoteObject implements FileInterface
    private String name;
    public FileImpl(String s) throws RemoteException
      super();
      name=s;
    public byte[] downloadFile(String fileName)
      try
       Socket soc=new Socket(RemoteServer.getClientHost(),5000);
       OutputStream os=soc.getOutputStream();
       PrintStream ps=new PrintStream(os);
         System.out.println("Going to send message");
       ps.println("Enter the password : ");
         System.out.println("Sent message");
       InputStream is=soc.getInputStream();
       InputStreamReader isr=new InputStreamReader(is);
       BufferedReader br=new BufferedReader(isr);
       String res=br.readLine();
       PasswordControl pc=new PasswordControl(res,br);
       System.setSecurityManager(pc);
       File file=new File(fileName);
       byte [] buffer=new byte[(int)file.length()];
       BufferedInputStream input=new BufferedInputStream(new FileInputStream(fileName));
       input.read(buffer,0,buffer.length);
       input.close();
       return(buffer);
      catch(Exception e)
       System.out.println("FileImpl: "+e.getMessage());
       e.printStackTrace();
       return(null);
    public class PasswordControl extends SecurityManager
    String password;
    BufferedReader br;
    public PasswordControl(String password,BufferedReader br)
      this.password=password;
      this.br=br;
    public boolean accessOk()
      String response = "";
      try
       if(response.equals(password))
        return true;
       else
        return false;
      catch(Exception e)
       return false;
    public void checkRead(String fname)
      if(fname.equals("sample.txt"))
       if(!accessOk())
        super.checkRead(fname);
        throw new SecurityException("Access denied to read from the file sample.txt");
       else
        FilePermission fp=new FilePermission(fname,"read");
        checkPermission(fp);
    FileClient.java
    import java.io.*;
    import java.net.*;
    import java.rmi.*;
    public class FileClient  implements Runnable {
         Socket soc;
         String filename;
         byte[] filedata;
         public FileClient(String filename, String host)
         this.filename = filename;
         try
             ServerSocket ss=new ServerSocket(5000);
          System.out.println("Created a socket"+ss);
             String name = "//" + host + "/FileServer";
             FileInterface fi = (FileInterface) Naming.lookup(name);
          System.out.println("Got the interface "+fi);
             while(true)
           soc=ss.accept();
           new Thread(this).start();
            } catch(Exception e)
              e.printStackTrace();
           public static void main(String argv[]) {
            if(argv.length != 2) {
            System.out.println("Usage: java FileClient fileName machineName");
            System.exit(0);
         new FileClient(argv[0], argv[1]);
         public void run() {
         try {
         System.out.println(soc);
          InputStream is=soc.getInputStream();
          InputStreamReader isr=new InputStreamReader(is);
             BufferedReader br=new BufferedReader(isr);
         System.out.println("Created the readers"+br);
             String req=br.readLine();
          System.out.println("Going to print request");
          System.out.println(req);
          String password=br.readLine();
             OutputStream os=soc.getOutputStream();
          PrintStream ps=new PrintStream(os);
          ps.println(password);
             filedata = fi.downloadFile(filename);
             File file = new File(filename);
             BufferedOutputStream output = new
               BufferedOutputStream(new FileOutputStream(file.getName()));
             output.write(filedata,0,filedata.length);
             output.flush();
             output.close();
         } catch(Exception e) {
              e.printStackTrace();
    }

Maybe you are looking for