Help ...how to get the file size on a server

Hi.I use this code to parse a file that is on a server.
The question is: how can i get the file size (bytes size)?
Thanks.
//Open the file for reading:
URL u = new URL(entry);
InputStream inputXML = u.openStream();
//Build document:
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(inputXML);

Try this instead:
URL u = new URL(entry);
URLConnection conn = u.openConnection();
// get the file size
int size = conn.getContentLength();
// open the input stream from the URLConnection (which is functionally the same as opening it directly from the URL)
InputStream inputXML = conn.getInputStream();
Shaun

Similar Messages

  • How to get the file size (in bytes) for all files in a directory?

    How to get the file size (in bytes) for all files in a directory?
    The following code does not work. isFile() does NOT recognize files as files but only as directories. Why?
    Furthermore the size is not retrieved correctly.
    How do I have to code it otherwise? Is there a way of not converting f-to-string-to-File again but iterate over all file objects instead?
    Thank you
    Peter
    java.io.File f = new java.io.File("D:/todo/");
    files = f.list();
    for (int i = 0; i < files.length; i++) {
    System.out.println("fn=" + files);
    if (new File(files[i]).isFile())
         System.out.println("file[" + i + "]=" + files[i] + " size=" + (new File(files[i])).length() ); }

    pstein wrote:
    ...The following code does not work. Work?! It does not even compile! Please consider posting code in the form of an SSCCE in future.
    Here is an SSCCE.
    import java.io.File;
    class ListFiles {
        public static void main(String[] args) {
            java.io.File f = new java.io.File("/media/disk");
            // provides only the file names, not the path/name!
            //String[] files = f.list();
            File[] files = f.listFiles();
            for (int i = 0; i < files.length; i++) {
                System.out.println("fn=" + files);
    if (files[i].isFile()) {
    System.out.println(
    "file[" +
    i +
    "]=" +
    files[i] +
    " size=" +
    (files[i]).length() );
    }Edit 1:
    Also, in future, when posting code, code snippets, HTML/XML or input/output, please use the code tags to retain the indentation and formatting.   To do that, select the code and click the CODE button seen on the Plain Text tab of the message posting form.  It took me longer to clean up that code and turn it into an SSCCE, than it took to +solve the problem.+
    Edited by: AndrewThompson64 on Jul 21, 2009 8:47 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How do I get the byte size of a server file before sending output via HTTP?

    I need to get the byte size of the file prior to streaming it. I can't seem to find a class/method I need. Basically, I have the path c:\\tomcat\\webapps\\documents\\sample.pdf in the servlet, I was hoping I could just use something from the File class but I couldn't find anything that seems to do the trick?
    thanks, in advance,
    Chuck

    maybe the source of the problem will help...I am trying to stream a PDF to IE and a blank page is being generated although all other file type work.
    I have found a lot of answers in the forum but no specific code examples. Here's what I have so far from picking through threads in here (can someone please show me how to get the byte size of the file so that I can assign it to the method response.setContentLength();?):
    String CONTENT_TYPE = " ";
         String target = " ";
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
         StringBuffer buf = new StringBuffer();
         HttpSession session = request.getSession();
         String file = request.getParameter("filename");
         target = file;
         int end = file.length();
    int beg = end-2;
         String type = file.substring(beg, end);
         if (type.equals("DOC")){
              CONTENT_TYPE = "application//vnd.msword";
         }else if (type.equals("XLS")){
              CONTENT_TYPE = "application//vnd.x-excel";
         }else if (type.equals("PPT")){
              CONTENT_TYPE = "application//vnd.ms-powerpoint";
         }else if (type.equals("PDF")){
              CONTENT_TYPE = "application//vnd.x-pdf";
         }else if (type.equals("MPP")){
              CONTENT_TYPE = "application//vnd.ms-project";
         }else if (type.equals("ZIP")){
              CONTENT_TYPE = "application//ZIP";
         }else if (type.equals("TXT")){
              CONTENT_TYPE = "text//plain";
         }else {
              CONTENT_TYPE = "text//html";
         //File f = new File(file);
         //int l = f.length();
         response.setContentLength(l); <----- supposedly this fixes my problem but I don't know how to get the byte szie of the file in an integer??
         // reset the response
         response.reset();
         response.setContentType(CONTENT_TYPE);
         try{
         // Get streams
         FileInputStream fileInputStream = new FileInputStream(target);
         ServletOutputStream servletOutputStream = response.getOutputStream();
         // Init byte count and array
         int bytesRead = 0;
         byte byteArray[] = new byte[4096];
         // Read in bytes through file stream, and write out through servlet stream
         while((bytesRead = fileInputStream.read(byteArray)) != -1) {
         servletOutputStream.write(byteArray, 0, bytesRead);
              servletOutputStream.flush();
         // Flush and close streams
         servletOutputStream.flush();
         servletOutputStream.close();
         fileInputStream.close();
         } catch (Exception e) {
         System.out.println(e.toString());

  • Programming help - how to get the read-only state of PDF file is windows explorer preview is ON?

    Programming help - how to get the read-only state of PDF file is windows explorer preview is ON?
    I'm developing an application where a file is need to be saved as pdf. But, if there is already a pdf file with same name in the specified directory, I wish to overwrite it. And in the overwrite case, read-only files should not be overwritten. If the duplicate(old) file is opened in windows (Win7) explorer preview, it is write protected. So, it should not be overwritten. I tried to get the '
    FILE_ATTRIBUTE_READONLY' using MS API 'GetFileAttributes', but it didn't succeed. How Adobe marks the file as read-only for preview? Do I need to check some other attribute of the file?
    Thanks!

    Divya - I have done it in the past following these documents. Please read it and try it it will work.
    Please read it in the following order since both are a continuation documents for the same purpose (it also contains how to change colors of row dynamically but I didnt do that part I just did the read_only part as your requirement) 
    http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/f0625002-596c-2b10-46af-91cb31b71393
    http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/d0155eb5-b6ce-2b10-3195-d9704982d69b?quicklink=index&overridelayout=true
    thanks!
    Jason PV

  • How to get the correct size of the loaded swf file?

    final public class main extends Sprite
      public function main()
       loaderInfo.addEventListener(Event.COMPLETE, _onLoadCompleted);
      private function _onLoadCompleted(event: Event): void
       var tw: int = stage.width;
       var th: int = stage.height;
       var tsw: int = stage.stageWidth;
       var tsh: int = stage.stageHeight;   
    Above is my simple as3 project in flex builder 3.
    My screen resolution is 1920*1080, when debugging, the swf is stretched to the full client area of the IE, but the stage.stageWidth is 500 and the stage.stageHeight is 375, both the stage.widht and stage.height are 0, who can tell me why and how to get the right size of the swf file, named the client area size of the IE in this situation?
    Thanks very much!

    The HTML wrapper might resize the SWF later, so wait a frame and check stageWidth/stageHeight again.
    Alex Harui
    Flex SDK Developer
    Adobe Systems Inc.
    Blog: http://blogs.adobe.com/aharui

  • How to get the byte[] size dynamically from the StreamMessage object

    Hi all,
    Using JMS, I am receiving the FDF file as StreamMessage from the queue and attaching it to the PDF file which is present in the local system.
    For that, I have written the code as follows:
    {color:#0000ff} Message msg = jmsTemplate.receive();
    if(msg !=null && msg instanceof StreamMessage)
    StreamMessage message = (StreamMessage) msg;{color}
    {color:#ff6600}//hardcoded the byte array size value
    {color}{color:#0000ff} byte[] bytes = new byte[{color:#ff0000}856{color}];
    System.out.println("read msg="+message.readBytes(bytes));{color}
    {color:#0000ff}PdfReader pdfreader = new PdfReader("D:\\Managing_Workflows_No_Comment.pdf");
    PdfStamper stamp = new PdfStamper(pdfreader, new FileOutputStream("D:\\12345.pdf"));
    FdfReader fdfreader = new FdfReader(bytes);
    stamp.addComments(fdfreader);
    {color} {color:#0000ff} stamp.close();
    {color}{color:#000000}The above code is working fine except with the hardcoded of {color:#ff0000}byte array{color}{color:#ff0000} size value{color} which is given in {color:#ff0000}RED{color} in color.
    Can anybody know, {color:#000000}*how to get the byte[] size dynamically from the StreamMessage*{color} object ?
    Any help would be highly beneficial for me !!!!
    Thanks and Regards,
    Ganesh Kumar{color}

    When you create your stream message you could add an property to your message, something like streamSize that would contain the number of bytes in your stream message. Then you could get this property from the message before declaring your array.
    Tom

  • AI CS3 Plugin: How to get the file format that is selected in the "save as" dialog??

    Hi,
    Someone please help me in getting the file format that is selected in the "save as" dialog. I wanted to retrieve it in the string format.
    I tried sAIDocument->GetDocumentFileFormat. But i'm unable to implement it correctly. Is there a better way or How do I implement this? Precisely, I wanna get the value as a string when the user selects "save as .pdf".

    Do you really need to know the file type? What about just checking the bit depth?
    var doc = activeDocument;
    if (doc.bitsPerChannel != BitsPerChannelType.EIGHT) {//Not 8 bit
    doc.bitsPerChannel = BitsPerChannelType.EIGHT;
    //do your save etc
    }else{
        //Ignore

  • Get the file size of a file on the server.

    okay.. for my download manager i need to get the file size. I tried using the available method of inputstream, and the getContentLength() of URLConnection, which worked but only for webpages. so does anyone know how to do this? Sun does it in SDM, but i dont think the source is included. ill download it again and check.
    thanks.

    content-length is not guaranteed to be anythingi dont think so. correct me if i am wrong..
    http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#s
    c4.4 states -
    " When a Content-Length is given in a message where a
    message-body is allowed, its field value MUST exactly
    match the number of OCTETs in the message-body.
    HTTP/1.1 user agents MUST notify the user when an
    invalid length is received and detected."
    this sort of guarantees that if a file is being
    downloaded the content-length gives the size of the
    file. i am able to confirm this by sniffing the
    traffic of my download manager.This is only guaranteed if the content length field is present. :-)
    However, looking two paragraphs up:
    'All HTTP/1.1 applications that receive entities MUST accept the "chunked" transfer-coding (section 3.6), thus allowing this mechanism to be used for messages when the message length cannot be determined in advance.'
    There is mechanism built in for cases where the size cannot be determined.
    Regards,
    Bhaveet

  • How to get the files in presentation server while uploading?

    how to get the files in presentation server while uploading?
    give me the function module name

    Hi,
    PARAMETERS:  P_FILE LIKE RLGRAP-FILENAME DEFAULT C_PRES.  "Prsnt Srvr
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR P_FILE.
      CALL FUNCTION 'WS_FILENAME_GET'
        EXPORTING
          DEF_PATH         = P_FILE
          MASK             = ',..'
          MODE             = '0 '
          TITLE            = 'Choose File'
        IMPORTING
          FILENAME         = P_FILE
        EXCEPTIONS
          INV_WINSYS       = 1
          NO_BATCH         = 2
          SELECTION_CANCEL = 3
          SELECTION_ERROR  = 4
          OTHERS           = 5.

  • I am trying to make a pdf of a file and I need to get the file size to be no bigger than 10MB. What is the best way to do this

    I am trying to make a pdf of a file and I need to get the file size to be no bigger than 10MB. Even when I save it, the image quality at minimum the file size is 10.9 MB. What is the best way to do this

    @Barbara – What purpose is that PDF for? Print? Web?
    If web purpose, you could convert CMYK images to sRGB. That would reduce the file size as well.
    A final resort to bring down file size is:
    1. Print to PostScript
    2. Distill to PDF
    That would bring file size down even more. About 20%, depending on the images and other contents you are using, compared with the Acrobat Pro method. If you like you could send me a personal message, so we could exchange mail addresses. I could test for you. Just provide the highres PDF without any downsampling and transparency intact. Best provide a PDF/X-4.
    I will place the PDF in InDesign, print to PostScript, distill to PDF.
    Uwe

  • [CS3][JS] How to get the file type of current document

    Hi,
    How to get the file type of current opening document (e.g., tif, jpeg, png) using JavaScript with Photoshop CS3.
    I am using file object the open the files one by one in the folder (the files sometimes don't have the extensions).
    If the current document is in tiff format then I need to convert to 8-bit, if its an Jpg image then needs to ignore the file.
    Regards,
    Karthik

    Do you really need to know the file type? What about just checking the bit depth?
    var doc = activeDocument;
    if (doc.bitsPerChannel != BitsPerChannelType.EIGHT) {//Not 8 bit
    doc.bitsPerChannel = BitsPerChannelType.EIGHT;
    //do your save etc
    }else{
        //Ignore

  • How to get the file name from Oracle B2B 10g

    Hi My requirement is I am getting a CSV file from Trading partner, I am using oracle 10g b2b to translate the data.
    In my BPEL 10g I am using AQ adapter to get the message from IP_IN_QUEUE.
    Now I want to get the file name Eg: SampleFile.dat of the CSV file in my BPEL process.
    I tried using the b2b.filename property in the receive activity and it is not getting the file name.
    <sequence name="main">
        <receive name="Receive_Note" partnerLink="GetB2BNote"
                 portType="ns1:Dequeue_ptt" operation="Dequeue"
                 variable="Receive_Note_Dequeue_InputVariable"
                 createInstance="yes">
                 <bpelx:property name="b2b.fileName" variable="WriteFileName"/>
        </receive>
      </sequence>
    Can you help me to get the file name from Oracle b2b 10g ?
    Thanks,
    b2b user

    Hi My requirement is I am getting a CSV file from Trading partner, I am using oracle 10g b2b to translate the data.
    In my BPEL 10g I am using AQ adapter to get the message from IP_IN_QUEUE.
    Now I want to get the file name Eg: SampleFile.dat of the CSV file in my BPEL process.
    I tried using the b2b.filename property in the receive activity and it is not getting the file name.
    <sequence name="main">
        <receive name="Receive_Note" partnerLink="GetB2BNote"
                 portType="ns1:Dequeue_ptt" operation="Dequeue"
                 variable="Receive_Note_Dequeue_InputVariable"
                 createInstance="yes">
                 <bpelx:property name="b2b.fileName" variable="WriteFileName"/>
        </receive>
      </sequence>
    Can you help me to get the file name from Oracle b2b 10g ?
    Thanks,
    b2b user

  • How to get the absolute path of logicalhost server domain on Windows?

    My logicalhost server domain behaves strangely. I am reading a file from collaboration definiton, that is located in the logicalhost/is/domains/domain1/config folder. I thought, that this folder is used as an application root folder so I can read files like ./file from there. And it worked.
    But then I've installed the domain as a Windows service, restarted the PC. When the domain1 gets started, I get exceptions saying that the file can't be found. Then I restart the domain (in domainmgr.bat) and it works again.
    I am pretty sure that using the absolute path will solve this issue, so my first question is: How to get the absolute path of logicalhost server domain on Windows?
    And my second question is: Why does this happen?

    The default folder for a Windows Service is the system32 folder contrary to the instance root folder when starting it as a normal process.
    That's the why, haven't tried the how, but you should be able to get the value by calling System.getProperty("com.sun.aas.instanceRoot").
    Hope this helps
    Paul

  • How to get the Change node in Production Server!!!!!

    Hi Guys,
    Kindly let me know how to get the Change node in Production Server for the Transaction Code Pe03 for generating the Acknowledgement No for the year 2008 .
    Plz provide me the steps how to get the Change Node for Acknowledgement No so tat i can get the configuration done.
    Regards
    Ansuman Mohanty.

    Hi Mr!
    If you want to generate the e-file feature 40ACK, do it in our Customization client box (Golden box) & save the request & move to Quality & production.
    Still if you need to workout only in Production, than with the help of Basis people you can get the Production change mode for 5 to 10 min time & can generate it. But mostly Basis people wont give us change mode for Production box ... with ur request they can do..try it.
    Did u collected 4 quarter TAN no's for 2008 Quarter...if not collect it & generate it at a time.
    All the best:-)
    Kind Regards,
    Saisree.S

  • How to get the absolute path of logicalhost server domain on Windows Sun

    i am reading a file from Xsql Folder, that is located in the logicalhost Sun\AppServer\domains\domain1\applications\j2ee-apps.(IN Sun Application Server)
    I am pretty sure that using the absolute path will solve this issue, so my first question is: How to get the absolute path of logicalhost server domain on Windows?
    i tried with System.getProperty("com.sun.aas.instanceRoot").
    but i am able to retrive Sun\AppServer\domains\domain1 upto this .i am unable to retrive Sun\AppServer\domains\domain1\applications\j2ee-apps.
    please suggest me how u can get absolute path in sun application server

    Take a look here

Maybe you are looking for

  • How to convert Windows 8.1 .exe file to ISO image for installation via Boot Camp?

    I have a late 2013 retina display MacBook Pro and want to use Boot Camp to run one piece of software that is run exclusively on Windows operating systems.  I have a Windows 8.1 download from MS that is an .exe file, and I need to convert it (I believ

  • Moving only part of iphoto library to external hard drive

    I would like to only move part of my iphoto library to an external hard drive.  Trying to archive my older pictures.  I know how to move the entire library but not so sure on how to move only parts of the library.  Do i need to create a second archiv

  • System Preferences Sharing Internet Airport

    System 10.4.11 In System Preferences>Sharing>Internet my wife's iBook lists three check box options: Built-in Ethernet, Built-in Firewire and Airport. My Powerbook with the same system does not list the Airport option. How can I add it? Thanks.

  • Nokia Bubbles now available

    As someone who missed Bubbles the first time round, before the Labs guys pulled it due to problems with QT, I was chuffed to see it is now available again on Nokia Labs.  Loaded first time on my N8 and is a great app. Really well-designed and useful.

  • How to download LabVIEW Full Development System 7.1 and tool kit

    I want to get the "LabVIEW Full Development System 7.1 and tool kit", Where Can I download it from? TIA