Java adds extra garbage data to downloaded files?

I have been trying to write a updater to my java program and everytime I download a file it adds data to the end. When downloading a small text file it adds (null) a bunch of times to the bottom of the file. When downloading a 175k text file called large.txt it breaks the format a little bit then adds part of the file to the bottom. If you download a zip file it corrupts it. Does anyone know why java adds crap to the bottom of downloaded files or can someone help me out please?
//testDownload.java
import java.util.*;
import java.io.*;
import java.net.*;
public class testDownload
     public static void main(String[] args)
     int count = 0;
          try
               System.out.println("Downloading file");
               java.io.BufferedInputStream in = new java.io.BufferedInputStream(
               new java.net.URL("http://saveourmacs.com/testfile/test.txt").openStream());          
               //new java.net.URL("http://saveourmacs.com/testfile/large.txt").openStream());          
               java.io.FileOutputStream fos = new java.io.FileOutputStream("test.txt");
               //java.io.FileOutputStream fos = new java.io.FileOutputStream("large.txt");
               java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
               byte data[] = new byte[1024];
               while(in.read(data,0,1024)>=0)
                    bout.write(data);
                    count++;
                    if (count % 1024 == 0)     // every meg
                         System.out.print (">");
               System.out.println();
               System.out.println("File downloaded");
               bout.close();
               in.close();
          catch (Exception e)
               e.printStackTrace();
               //System.exit(-1);
}

You always write chunks of 1024 bytes; what if the last chunk read was less than 1024 bytes? Hint: use the return value of the read( ... ) method.
kind regards,
Jos
Edited by: JosAH on May 28, 2009 3:37 PM

Similar Messages

  • In Firefox 4 how can I cause the date on downloaded files to be the current date? (Some are and some are not. In FF3 the dates were ALWAYS the current ones.)

    In Firefox 4 how can I cause the date on downloaded files to be the current date? (Some are and some are not. In FF3 the dates were ALWAYS the current ones.)
    == This happened ==
    Every time Firefox opened
    == I upgraded to Firefox 4 (beta)

    Firefox 3.6.* and earlier set the downloaded file's modification time to the current time. In Firefox 4.0 the behavior has been changed, if a server returns a timestamp telling when the file was last modified (Last-Modified header), it is used instead.
    You can revert to the previous behaviour by using the [https://addons.mozilla.org/en-US/firefox/addon/93121/ Download Timestamp] add-on.

  • How can servlet return data as download file from browser ? !!! URGENT !!!

    My servlet query data from database and would like to return the data as text file.
    How can I return data to the browser as user click a file to download ?
    How can I set the file name ? (default name is the servlet name that I don't want it to be)
    Which content type should I return to browser to prevent browser to display data immediately but save instead ?
    Thank you very much !

    I am having the same issue. Did you ever discover a way to change the "file name" in the browser. I've tried changing numerous HTTP header fields, to no avail.
    Marc

  • This is how to add extra Exif data to Aperture :-)

    Folks
    Often I need additional Exif data in Aperture - which is not available in the standard install.
    For example - exactly which lens did I use - not just a focal lenght - which might be any one of various lenses I have.
    Or - which focus point was used?
    The list is endless...
    If you are interested - go to this thread in dpreview
    http://forums.dpreview.com/forums/read.asp?forum=1017&message=22939488
    A neat combination of an AppleScript and ExifTool
    Go for it
    Brian

    Hi,
    I'm the "author", if you can call it that, since most of the script is, as someone earlier mentioned, Brett Gross' work. I was the one that glued exiftool to it and got it working with my Aperture setup. I am looking at the various problems that have popped up on dpreview and with personal correspondence and trying to find solutions.
    But it isn't easy. As Charles said, the Aperture dictionary isn't helpful in that regard. And with the flexibility that Aperture provides in naming is the curse here. And all the variables with versions, external edits, etc. It gets very complicated. But if you look at the thread on dpreview, someone has possibly found a way to query the SQL database to make it all work smoothly.
    It is very easy to do this stuff at import. I am just putting the finishing touches on an Automator action to import the files and add the EXIF data (it will even query GeoNames and add the city, state & country IPTC data if there is GPS data present in the file).

  • How do i add time and date to target file

    hello,
    1. When do we generally go for FCC?
    2. Is it possible to assign field seperator without FCC on the reciever side file adapter?
    3. how do I add timestamp as well as DATE to the target file?
    thnks
    venkat

    Hi venkat
    1. When do we generally go for FCC?
        we can do the FCC at sender side as well as at the receiver side.
        Sender side: we do the FCC at the sender side only if we are getting a flat file   from the sender, and so that it can be understand by the XI,because XI can understand only the XML.
         Receiver side:we do the FCC at the receiver side only if the receiver requires the flat file.
    2. Is it possible to assign field seperator without FCC on the reciever side file adapter?
    no, it is not possible.
    3. how do I add timestamp as well as DATE to the target file?
    if you want to add date and time in the target file for this you have to select the parameter
      File Construction Mode* : AddTimeStamp
    in the processing parameters of the file adapter(Receiver).
    Thanks
    Rinku

  • How to add YYMMDD format date to the file name

    Hi,
    I need genrate the file with date suffixed to its name in YYMMDD format. The add time stamp is adding it till YYYMMDD-HHMMSSS.
    How can I change this format to the required one? Any suggessions.
    Thanks.
    Sri

    hi,
    you can create the whole filename (whatever you need)
    in the mapping (in a UDF) using adapter specific message attributes
    there are many blogs describing how to do that Dynamic Configuration of Some Communication Channel Parameters using Message Mapping
    Regards,
    Michal Krawczyk

  • No date in downloaded files?

    Hi, when i download a new file. It is listed as ¨without a date¨
    If it arranged by date, the first archives than appear are from yestarday and today archives are listed in the botton.

    MacBook Air OSX 10.9.3. 
    I've notice this only recently, the last month or so. Downloads no longer are sorted by date, I have to check the undated to find them.

  • How to add Yesteday's date in AL11 File name ?

    Hi Experts,
    Can anyone please reply to my Query ?
    We have to generate the *.TXT file as an output of Open Hub Destination.
    For this the File Naming convention should be Yesterday's date + .TXT. ( for example if today's date is 27.07.2011 then the file name should be 20110726.TXT).
    Here I could generate the file name using <YYYY><MM><DD> for today's only ( 20110727.TXT). But We need to generate the Yesterday's date here..
    I tried to create the Function module ( FILENAME_EXIT_TEST) as suggested in F1 on that Physical Location input area. And I tried to give the Physical location as <F=FILENAME_EXIT_TEST>.TXT.
    But I'm getting the error as " The Function Module doesnot exist" or "Function Module FILENAME_EXIT_TEST is unknown".
    But I'm sure the FM is available and activated already.
    Could you please let me know, How to fix this issue.
    NOTE: I have created this Function Module with Export parameter as OUTPUT and DATS Associated type. In the Source code I have written as OUTPUT = SY-DATUM - 1.
    Edited by: jayaprakash j on Jul 28, 2011 2:30 PM

    Hi All,
    I got the solution.
    The code which i had written in the FM is wrong.
    OUTPUT = SY-DATUM - 1. // Wrong.
    The correct one is below :
    DATA: Temp TYPE SY-DATUM.
    Temp = SY-DATUM - 1.
    OUTPUT = Temp.
    And after that, in FM's Export tab, it should be Export parameter as OUTPUT and checked the "Pass value" check box.
    For the Physical File : <F=TEST>.txt.
    Here the FM which i created was FILENAME_EXIT_TEST.
    When I am calling the corresponding Logical file in the APD, It is working fine.
    Thanks for your inputs.

  • How do i use Java to read the data in XML files?

    Hi,
    I'm rather interested in using XML in my javacodes, as i think it will be of more OO.
    I want to make use of XML in my javacodes,
    but i don't know how to start doing it, so i hope someone would be able to enlighten me on this,
    =)
    Some examples would be perfect

    Humm interesting...well here is the link to Sun's tutorial on how to use maipulate an XML document using Java's jaxp api.I hope this will give u a hint.
    http://java.sun.com/xml/tutorial_intro.html
    Khalid

  • Fix downloaded files permissions on Windows 7

    Almost every time I download a file from various sources, Firefox adds a padlock to the downloaded file icon. This means that the file can only be accessed by the current user unless I change back the file permissions manually.
    Is there any way of stop the downloads from changing their file permissions? I've only noticed this happening for a week or so, currently I'm on Firefox beta 26.0

    You can try to set the browser.download.manager.scanWhenDone pref to false on the <b>about:config</b> page to prevent Firefox from adding zone identifier data to the downloaded files.
    See:
    *http://kb.mozillazine.org/Unable_to_save_or_download_files

  • Path and file name problem when I want to download files from html

    Hi all,
    I want to write a small program to allow users download files from jsp file
    but the following files don't work .
    <%@ page language="java" import="java.net.*,java.io.*"%>
    <%@ page import ="java.util.*"%>
    <%
    try
    String SContent = request.getParameter("click");
    String SDocName = "temp.doc"; //  out put file File Name
    ServletOutputStream stream= response.getOutputStream(); // Getting ServletOutputStream
    response.setContentType("application/msword"); // Setting content type
    response.setHeader("Content-disposition","attachment;filename=\"" +SDocName+"\""); // To pop dialog box
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(SContent));
    int c;
    while ((c = in.read()) != -1){
               stream.write(c);
    in.close();
    stream.flush();
    catch(final IOException e)
    System.out.println ( "IOException." );
    catch(Exception e1)
    System.out.println ( "Exception." );
    %>I am so confuse, what is the path and file name I sould give ? for example my click should equal to http://******/Test/display.jsp?click=00-1

    Hi all,
    I got error at
    java.lang.IllegalStateException: getOutputStream() has already been called for this response
         org.apache.coyote.tomcat5.CoyoteResponse.getWriter(CoyoteResponse.java:599)
    if I want ot download file from html file.
    String SContent = request.getParameter("click");
    if I hard code like follow it work fine.
    String SContent ="C:/Project Coding.doc";
    what mistake I make.
    Thank you!

  • How to print out the data from the file ?

    hi all,
    i have upload my file to here :
    [http://www.freefilehosting.net/ft-v052010-05-09 ]
    anyone can help me to print out the data from the file ?
    the content of the file should be like this :
    185.56.83.89 156.110.16.1 17 53037 53 72 1
    and for the seven column is
    srcIP dstIP prot srcPort dstPort octets packets

    hi all,
    i have try to do this
    public static void Readbinary() throws Exception
              String file = "D:\\05-09.190501+0800";
              DataInputStream dis = new DataInputStream(new FileInputStream(file));
              //but then how to read the content ??????can you give me more hint ?????
    i have find the netflow v5 structure by C
    struct NFHeaderV5{
    uint16_t version; // flow-export version number
    uint16_t count; // number of flow entries
    uint32_t sysUptime;
    uint32_t unix_secs;
    uint32_t unix_nsecs;
    uint32_t flow_sequence; // sequence number
    uint8_t engine_type; // no VIP = 0, VIP2 = 1
    uint8_t engine_id; // VIP2 slot number
    uint16_t reserved; // reserved1,2
    struct NFV5{ 
    ipv4addr_t srcaddr; // source IP address
    ipv4addr_t dstaddr; // destination IP address
    ipv4addr_t nexthop; // next hop router's IP address
    uint16_t input; // input interface index
    uint16_t output; // output interface index
    uint32_t pkts; // packets sent in duration
    uint32_t bytes; // octets sent in duration
    uint32_t first; // SysUptime at start of flow
    uint32_t last; // and of last packet of flow
    uint16_t srcport; // TCP/UDP source port number or equivalent
    uint16_t dstport; // TCP/UDP destination port number or equivalent
    uint8_t pad;
    uint8_t tcp_flags; // bitwise OR of all TCP flags in flow; 0x10
    // for non-TCP flows
    uint8_t prot; // IP protocol, e.g., 6=TCP, 17=UDP, ...
    uint8_t tos; // IP Type-of-Service
    uint16_t src_as; // originating AS of source address
    uint16_t dst_as; // originating AS of destination address
    uint8_t src_mask; // source address prefix mask bits
    uint8_t dst_mask; // destination address prefix mask bits
    uint16_t reserved;
    but how to translate the structure to java,then get the data from the file ?
    Edited by: 903893 on Dec 21, 2011 10:52 PM

  • JAVA mapping using SAX parser adds extra tags

    Hi,
      We are using  java mapping using a SAX parser.It works well in standalone application ie it parses correctly and gets our desired xml structure and the xml is well formed too but when we import it in XI as a jar file it does not throw any errors but adds extra start tags, as a result the output xml is not well formed.XI is adding extra start tags.
    If any one else has faced a similar situation please help.
    Regards,
    Anirban.

    Hi Roberto,
    Thank you for the response.
    As I said, it doesnt throw any error. It is working perfectly in standalone application. But when we deploy it to XI Server, it is not forming the well formed XML. We too are puzzled by this situation.
    Okay, i will explain my scenario here.
    The following is my input XML to the java pgm..
    <Header>
    </Header>
    <Body>
    </Body>
    <SubBody1>
    </SubBody1>
    <SubBody2>
    </SubBody2>
    <SubBody3>
    </SubBody3>
    <SubBody4>
    </SubBody4>
    <Trail>
    </Trail>
    The desired output is
    <Header>
      <Body>
         <NameChanged1>
            <NameChanged2>
    <SubBody3>
    <SubBody4>
    </SubBody4>
    </SubBody3>
    </NameChanged2>
    </NameChanged1>
    <Trail>
    </Trail>
    Just look at the SubBody2 and SubBody1 node, its tag name has been changed in the output XML. Thats y i have decided to use java mapping instead of message mapping.
    I have developed the code for everything, i.e for changing the tag name and for forming the nested xml and it is working fine as a standalone application. But while deploying it to XI, the output is not well formed. I dont know the reason for it. Even I have checked the cardinality of the output Data types, that I have created. Its perfectly okay with all.
    Any Ideas???
    Regards,
    Anirban

  • Problem in Download data into Excel File

    Hi Friends,
    I have one doubt on WDJ.
             I have got the data from the Back and display the data into Table UI Element. Depending upon po_status equals to OA Pending that time conf_Ship_date Column is Empty. That time we can Select All Checkbox Click on Download Button Excel file is not download. Why it not download? Conf_Ship_date Column is Empty. Conf_Ship_date Column is data available that time data download into Excel File.
    My Req: if Conf_Ship_date Column is empty that time click on Download that data will download in to Excel. In Excel Conf_Ship_date Column will display in NULL or 00.00.0000 Like this also.
    Code:ExcelEle.setConf_Shp_Date(StockEle.getConf_Shp_Date()); 
    This means I am getting date from PoDetails_OutTab(StockEle)this node and add this date to PoDetails_ExcelData(ExcelEle) this node.Finally the date will available in PoDetails_ExcelData this node. By Using this node I will download data.
    How to do this work?
    Regards
    Vijay

    Hi Arun,
    For Example in Table 4 rows and 14 columns data is available. Select all check boxes click on download button total 4 rows and 14 columns data is downloaded.
    Table 4 rows and 14 columns data is available. But in some cells data not available in that time I m getting null values from ECC System. That time I am not able to download.
    In Particularly this problem I am getting only date colums.
    So now I have develop this code
    public void onActiondownloadToExcel(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActiondownloadToExcel(ServerEvent)
         IPrivatePO_Details_ResultView.IPoDetails_ExcelDataNode ExcelNode = wdContext.nodePoDetails_ExcelData();
         IPrivatePO_Details_ResultView.IPoDetails_ExcelDataElement ExcelEle; 
         IPrivatePO_Details_ResultView.IPoDetails_OutTabNode StockNode = wdContext.nodePoDetails_OutTab();
         IPrivatePO_Details_ResultView.IPoDetails_OutTabElement StockEle ;
         for(int i = 0 ;i<StockNode.size();i++)
         StockEle = StockNode.getPoDetails_OutTabElementAt(i);
         if(StockEle.getCheckBox()== true)
         ExcelEle = ExcelNode.createPoDetails_ExcelDataElement();// Create Element
         if(StockEle.getConf_Shp_Date()==null)
         java.sql.Date deliverydate1=new java.sql.Date(0,0,0);
         ExcelEle.setConf_Shp_Date(deliverydate1);
         else
         ExcelEle.setConf_Shp_Date(StockEle.getConf_Shp_Date()); 
    By using this code i have to download total Records but in this Conf_Shp_Date colums i am getting 31-12.1899 this output in Excel. But i need in Excel to print Null or 00.00.0000 like
         ExcelEle.setQuantity(StockEle.getQuantity());
         ExcelEle.setDeliv_Date(StockEle.getDeliv_Date());
         if(StockEle.getExpt_Shp_Date()==null)
         java.sql.Date deliverydate2=new java.sql.Date(0,0,0);
         ExcelEle.setExpt_Shp_Date(deliverydate2);
         else
         ExcelEle.setExpt_Shp_Date(StockEle.getExpt_Shp_Date());
         ExcelEle.setVendor_Material(StockEle.getVendor_Material());
         ExcelNode.addElement(ExcelEle);
         if(ExcelNode.size()>0)
         wdThis.wdGetCO_POPendingController().downloadData(wdContext.nodePoDetails_ExcelData());// This is for Downalod data Method
         wdThis.wdGetCO_POPendingController().DownLoadToExcel();// This is for Open Popup Window
         wdContext.nodePoDetails_ExcelData().invalidate();
         else
         wdComponentAPI.getMessageManager().reportException("Please select any one po item from the table",true);
        //@@end
    Regards
    Vijay
    Edited by: KalluriVijay on May 18, 2010 10:05 AM

  • [Verifying Downloads] Java-Downloaded file not same filesize as on server

    This is in the security forum, but really involves a few details:
    1.) My program downloads files from a server
    2.) I have precalculated hash md5 values and file sizes in a .cfg file in the server which is also downloaded
    3.) The md5 is calculated of the downloaded files
    4.) The filesize is checked and the md5s are checked
    I have 4 client windows computers I've tested this on. It worked on 3. The fourth has a strange behavior: About every other file would have ~ 8 additional bytes in the filesize. I have no idea where those bytes are coming from, everytime it redownloads, same filesize, albeit 8 bytes too big. Therefore, the Md5 is screwed up.
    Here's my downloading from server code:
    OutputStream out = null;
              InputStream  in = null;
              try {
                   URLConnection dat = online.openConnection();
                   local.getParentFile().mkdirs();
                   out = new FileOutputStream(local);
                   while(true){
                        try {
                             in = dat.getInputStream();
                             break;
                        } catch (ConnectException e){
                             System.err.println("Couldn't contact server!");
                   byte[] buffer = new byte[1024];
                   int numRead;
                   tsecago = System.nanoTime();
                   readbytessecAgo = -1;
                   while ((numRead = in.read(buffer)) != -1) {
                        out.write(buffer, 0, numRead);
                        readbytes += numRead;
              } catch (Exception e){
                   e.printStackTrace();
              } finally {
                   try {
                        if (in != null) {
                             in.close();
                        if (out != null) {
                             out.close();
                   } catch (IOException ioe) {
              }SO, my solution was as follows:
    1.) Download file once and check md5 & filesize
    2.) If failed, download file AGAIN and check md5 & filesize
    3.) If failed 2x, download file for last time and check filesize - if the filesize is within 40 bytes of the actual file, allow it.
    This now works on all 4 computers, and as far as I can tell the downloaded files are wholly correct.
    But this is really annoying! Why is the above download code producing 8 extra bytes?!

    Thanks for your reply, Timo, and John, the same file downloading is working fine with my Integrated weblogic server, but the same application when i deployed in my DEV server i am getting the error.
    Code which i am trying to download file is
    public void downloadCardInserts(FacesContext facesContext,
    OutputStream outputStream) throws FileNotFoundException,
    IOException {
    // Add event code here...
    UploadedFile filename=(UploadedFile)browseFile.getValue();
    String fname=filename.getFilename();
    String fname1="//bwi-wfp-v01/Apps/SCII/TEST/LOG/Cards/RENEWAL/"+fname;
    System.out.println("file name11111:"+fname1);
    FileInputStream in = new FileInputStream(new File(fname1));
    byte[] buffer = new byte[1024];
    int bytes = in.read(buffer);
    while (bytes >= 0) {
    outputStream.write(buffer, 0, bytes);
    bytes = in.read(buffer);
    }

Maybe you are looking for