Problem using setRequestProperty on a url connection, how can I fix it?

From what I've read on it I thought I did everything the right way. I'm just starting out with the networking aspect of Java. What I'm trying to do is download only a portion of a file. For right now I'm just worried about downloading the end of a file starting from a value I enter manually. I read that I should use the setRequestProperty to set the start position of the file I'm download. For some reason it isn't working for me. It's still download the entire file. Can anyone give me some insight into what I'm doing wrong? I've commented what I think is happening in each line of the code, if someone could verify where I'm correct and where I'm wrong at that would be helpful too. Thank you.
import java.io.*;
import java.net.*;
public class FileDownload2 {
     public static void download() {
          OutputStream out = null;
          RandomAccessFile file = null;
          URLConnection conn = null;
          InputStream  in = null;
          try {
                        URL url = new URL(""); //create a new url
               conn = url.openConnection();//set url up to be opened
               conn.setRequestProperty("Range", "921600-"); // send a header-request
               in = conn.getInputStream(); //open the connection to the file
               byte[] buffer = new byte[1024];//create a buffer to hold bytes from the file
                out = new FileOutputStream("test");//create a new file to write the bytes to
               int numRead;
               long numWritten = 0;
               while ((numRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, numRead);
                    numWritten += numRead;//while there is still data read from the buffer and write the bytes to the file
          } catch (Exception exception) {
               exception.printStackTrace();
          } finally {
               try {
                    if (in != null) {
                         in.close();//close the inputstream
                    if (out != null) {
                         out.close();//close the file
               } catch (IOException ioe) {
     public static void main(String[] args) {
               download();//call method download
}Edited by: Secondtimearound on May 3, 2008 9:05 AM

Thanks! I ended up finding that on my own. I'll still give you the points if you want them because you gave the right answer. LOL I do have another question though. I only want to download part of a file and it seems to work fine with .mp3 files, I'm guessing because they were designed to play from any part of the file. However, when the program downloads only a part of a video file the video won't show. Sometimes the audio will still download that goes along with the video file. I read in another forum that the reason p2p programs can preview a video file is because they download the begining and end of the file. My question is, how can determine how much of the beginning and end of the file needs to be downloaded in order for the video file to play? I'm guessing there's some type of header file in the video but how to I download just that first? Then, I'm thinking I would have to use threads to download the different parts then combine them or something. I'm not sure. Any help would be appreciated. Thanks.

Similar Messages

  • I cannot access my face time.When i do that I get a message that I cannot sign in and to check my internet connection. how can i fixed that?

    i cannot access my face time.When i do that I get a message that I cannot sign in and to check my internet connection. how can i fixed that?

    What version of iTunes are you using?  The latest is 10.6.3. In iTunes, choose Help -> About iTunes to check the version number. If it's lower than 10.6.3, download the latest version from here.
    B-rock

  • I just updated my iphone to IOS 7 and cannot get my imessage to work, it keeps saying "waiting for activation" nothing i have read online has helped me try to fix the problem. why is it doing this and how can i fix it?

    I just updated my iphone to IOS 7 and cannot get my imessage to work, it keeps saying "waiting for activation" nothing i have read online has helped me try to fix the problem. why is it doing this and how can i fix it?

    Here's a good troubleshooting article about imessage "waiting for activation".
    http://support.apple.com/kb/TS4268

  • Hi there. I shot with a nikon d7000. The clips look great on the viewer but quite bad on canvas (also after its been exported) I converted my clips to apple pro res 422 using mpeg streamclip. The size I used was 1920 x 1080. How can I fix these?

    Hi there. I shot with a nikon d7000. The clips look great on the viewer but quite bad on canvas (also after its been exported) I converted my clips to apple pro res 422 using mpeg streamclip. The size I used was 1920 x 1080. How can I fix this?

    This is the clip:
    This is the sequence:
    I know they both should match. Question is, should I re convert the clips in mpeg using different size settings? Or should I change the sequence settings? how?
    Thanks A LOT.

  • I just downloaded ios7 now i can only use the phone with the speaker, how can i fix this?

    I just downloaded ios7 now i can only use the phone with speaker, how can i fix this?

    x

  • JTable size problems due to layout/grid...how can I fix?

    This is my code. When the button "Modify Entries" is pressed, it shows a JTable that imports a file called, "entries.data". The items in this file can be read and saved using this program. The problem is that the table is so small when it first opens. How can I set all my buttons to the very bottom of the form and make the table take up more space at the top? It looks to me as if this layout is treating it with the same dimensions as the buttons'.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import java.util.*;
    import java.io.*;
    public class CPT extends JPanel implements ActionListener
        protected JButton ModifyEntriesButton, ViewEntriesButton, SearchEntriesButton, SaveButton, BackButton;
        private final static String newline = "\n";
        private DefaultTableModel model;
        public CPT ()
            super (new GridLayout (10, 0));
            model = new PropertiesModel ("entries.data");
            ModifyEntriesButton = new JButton ("Modify Entries");
            ModifyEntriesButton.setVerticalTextPosition (AbstractButton.TOP);
            ModifyEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            ModifyEntriesButton.setToolTipText ("Click this button to modify database entries.");
            ModifyEntriesButton.setMnemonic (KeyEvent.VK_M);
            ModifyEntriesButton.setActionCommand ("ModifyEntries");
            ModifyEntriesButton.addActionListener (this);
            ViewEntriesButton = new JButton ("View Entries");
            ViewEntriesButton.setVerticalTextPosition (AbstractButton.CENTER);
            ViewEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            ViewEntriesButton.setToolTipText ("Click this button to add view all database entries.");
            ViewEntriesButton.setMnemonic (KeyEvent.VK_V);
            ViewEntriesButton.setActionCommand ("ViewEntries");
            ViewEntriesButton.addActionListener (this);
            SearchEntriesButton = new JButton ("Search Entries");
            SearchEntriesButton.setVerticalTextPosition (AbstractButton.BOTTOM);
            SearchEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            SearchEntriesButton.setToolTipText ("Click this button to search through all database entries.");
            SearchEntriesButton.setMnemonic (KeyEvent.VK_S);
            SearchEntriesButton.setActionCommand ("SearchEntries");
            SearchEntriesButton.addActionListener (this);
            SaveButton = new JButton ("Save");
            SaveButton.setVerticalTextPosition (AbstractButton.TOP);
            SaveButton.setHorizontalTextPosition (AbstractButton.RIGHT);
            SaveButton.setToolTipText ("Click this button to save database entries.");
            SaveButton.setMnemonic (KeyEvent.VK_S);
            SaveButton.setActionCommand ("Save");
            SaveButton.addActionListener (this);
            BackButton = new JButton ("Back");
            BackButton.setVerticalTextPosition (AbstractButton.BOTTOM);
            BackButton.setHorizontalTextPosition (AbstractButton.RIGHT);
            BackButton.setToolTipText ("Click this button to return to the main menu.");
            BackButton.setMnemonic (KeyEvent.VK_B);
            BackButton.setActionCommand ("Back");
            BackButton.addActionListener (this);
            add (ModifyEntriesButton);
            add (ViewEntriesButton);
            add (SearchEntriesButton);
        class PropertiesModel extends DefaultTableModel
            public PropertiesModel (String filename)
                addColumn ("Item Number");
                addColumn ("Description");
                addColumn ("Price");
                //Fill model with data from property file
                Properties props = readFile (filename);
                if (props != null)
                    Enumeration coll = props.keys ();
                    while (coll.hasMoreElements ())
                        String property = (String) coll.nextElement ();
                        String value = props.getProperty (property, "");
                        addRow (new Object[]
                            property, value
        private Properties readFile (String filename)
            try
                Properties props = new Properties ();
                props.load (new FileInputStream (filename));
                return props;
            catch (IOException ioe)
                return null;
        private boolean saveFile (String filename)
            try
                Properties props = new Properties ();
                for (int i = 0 ; i < model.getRowCount () ; i++)
                    props.put (model.getValueAt (i, 0), model.getValueAt (i, 1));
                props.store (new FileOutputStream (filename), null);
                return true;
            catch (IOException ioe)
                return false;
        public void actionPerformed (ActionEvent e)
            if ("ModifyEntries".equals (e.getActionCommand ()))
                removeAll ();
                add (new JScrollPane (new JTable (model)), BorderLayout.CENTER);
                add (SaveButton);
                add (BackButton);
                invalidate ();
                updateUI ();
            if ("ViewEntries".equals (e.getActionCommand ()))
                removeAll ();
                add (BackButton);
                invalidate ();
                updateUI ();
            if ("SearchEntries".equals (e.getActionCommand ()))
                removeAll ();
                add (BackButton);
                invalidate ();
                updateUI ();
            if ("Back".equals (e.getActionCommand ()))
                removeAll ();
                add (ModifyEntriesButton);
                add (ViewEntriesButton);
                add (SearchEntriesButton);
                invalidate ();
                updateUI ();
            if ("Save".equals (e.getActionCommand ()))
                if (saveFile ("entries.data"))
                    JOptionPane.showMessageDialog (null, "File saved successfully.");
                else
                    JOptionPane.showMessageDialog (null, "File could not be saved!");
        // Create the GUI and show it. For thread safety,
        // this method should be invoked from the
        // event-dispatching thread.
        private static void createAndShowGUI ()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated (true);
            //Create and set up the window.
            JFrame frame = new JFrame ("Swisha Computer House");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new CPT ();
            newContentPane.setOpaque (true); //content panes must be opaque
            frame.setContentPane (newContentPane);
            //Display the window.
            frame.pack ();
            frame.setSize (300, 300);
            frame.setVisible (true);
        public static void main (String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater (new Runnable ()
                public void run ()
                    createAndShowGUI ();
    }Hey, and if anyone knows how to get the first column's numbers from the file to show up in descending order (1 through to, say, 500), please let me know.
    Thank you for any help.

    It looks to me as if this layout is treating it with the same dimensions as the buttons'.Thats the way a GridLayout works.
    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers. You can mix an match individual Layout Managers to get the effect desired.
    I would suggest you need to change your design. Your code for continually removing and adding components is not the best design. You should probably have a panel with all your buttons. Then you would have different panels for each of your sub functions. The display of these panels would be controlled by a Card Layout. The tutorial has working examples of this.
    You can't use a Properties file to save data from the table (at least not the way you are attempting to use it). I gave you a solution in your last posting.

  • I sometimes get Error 42 when opening a TCP connection - how can I fix this ?

    In my Labview application I am opening a TCP connection in an identical way to the Data Client example. I am using a direct connection to external equipment using an ethernet crossover cable. The error occurs on at least 2 different PCs.
    The error can occur regardless of whether anything is connected to the ethernet port of the PC.
    The only way I have found to clear the error is to power down the PC and restart with a connection to the office LAN. Then I can swap back to the crossover cable and talk to the remote equipment once again, ...unitl the next time the error occurs.
    I have LabView 6.0 running on Win98.
    Any help greatly appreciated.

    Jeremy,
    Thanks for taking the time to answer
    I already checked the link you suggested but I am connecting to my remote instrument with a 2m cross-over cable.
    I Have looked into this a little further, it seems the sequence of events is as follows -
    1. After some hours the connection gets lost.
    2. TCP Read returns error 66 - Connection was closed by peer.
    3. If I try to restart my program I get Error 42 at TCP open Connection.
    4. Rebooting the PC doesn't clear the error 42 problem.
    5. If I try to PING my instument I get "Host unreachable".
    6. I have to "refresh" my network card by connecting to our LAN and either opening a file on another PC or simply sending a PING to another PC.
    6. I can then reconnect my remote instrument via cross-over cable
    and we're up and running for another few hours.
    I get the same problem on two different PCs with different NICs and different OS (Win98 and WinME)
    I am assuming that because a reboot has no effect that its not a memory allocation problem.
    It seems like LabView stops talking to the NIC and then gets locked out some how.
    Any other tips ?

  • My Eye Dropper STILL does not work in CS5 while using Lion with one monitor. How can i fix this?!?

    Hello everyone!
    This is my first post because i have grown very disgruntled at the fact that my eye dropper does not work my Premiere CS5. I would use the Ultra Key a lot but now I obviously can not really use it too well because of no eye dropper. I saw that this problem existed after the Lion update but this really should have been fixed by now. I am using only one monitor also. Is there a way to fix this or is this still known to be broken? I paid good money for CS5 and would be very upset if the only way around this is to pay MORE money to upgrade to CS5.5. Thanks.

    Thanks for the response Stephen! I find this very bad on Adobe's part though if they do not feel obligated to fix CS5 for Lion. Eye dropper is a major part of Premiere and i am going to be very dissapointed if they do not fix that. With the amount of money the Suite costs, they definitly should make sure it runs well for quite a few years. I would expect a copy of CS4 to be able to work too. If they do not fix CS5 all because the OS has changed basically tells me that every 2 years or so, they stop caring about their product.
    Sorry i sound so bitter about this but it has really hurt my workflow. Ultra key is great and something that FCP does not have so it has the edge in that respect, but now i can not even properly use it. I have to go into After Effects with the same clip, use that eyedropper to get the correct color # and then copy and paste the # into Ultra Key in Premiere which is very very annoying and slows down my system quite a bit.
    So basically, they are probably not going to ever fix this? Thanks again

  • Firefox will not load any website, it says unable to connect, how can I fix this?

    Every url I type in it comes up with unable to connect and firefox cant establish a connection! its like it's not even got a connection but i can get on the internet at the same time with internet explorer! I have tried disabling the IPv6 and Prefetch and still unable to connect! i have changed the proxy to no proxy and still unable to connect.

    A possible cause is security software (firewall) that blocks or restricts Firefox or the plugin-container process without informing you, possibly after detecting changes (update) to the Firefox program.
    Remove all rules for Firefox from the permissions list in the firewall and let your firewall ask again for permission to get full unrestricted access to internet for Firefox and the plugin-container process and the updater process.
    See:
    *https://support.mozilla.com/kb/Server+not+found
    *https://support.mozilla.com/kb/Firewalls

  • MY computer sayd that it is connected to the internet in the upper right hand corner, but when I try to open safari, it says that it is unable to connect. how can i fix that?

    I just got this computer today, everything works fine but I cannot connect to the internet. The Wi-Fi thing in the top right corner tells me that im connected, but when I try to open Safari, it says that I am not able to connect to the internet. I have done everything the computer has told me, and i still can't connect. I need help please!!

    The problem lies between your router and the ISP.
    Pull the modem or router/modem power plug, wait about 30 seconds and plug it back in to establish a new connection to the ISP.
    Try another website, another device and see if that works if not then call your ISP for assistance and/or reconfigure the router.
    If your router isn't secure and you had bad leechers the ISP might have suspended the access or perhaps met the monthly data cap rate.
    See these links too.
    WiFi, Internet problems, possible solutions
    WiFi security issues, at home and WiFi hotspots

  • HT1218 after Lion update my airport get a time out every 3 min. and loos connection - how can i fix it?

    Hej
    After I updated to Lion OS my airport get time out and I loos connection al the time . can you help med to fix this problem?
    Thanks

    I turned on data roaming like you had said. Still didn't work. I tried calling the customer service support number with Verizon the other day. I was told by technical support to head over to a local Best Buy and have the reps at the Samsung Experience uninstall the updated software and install it again but on ground not over the network. I went and did that today and still nothing. I'm still on 3g. The rep was puzzled as to why my phone was on global network instead of the LTE/CDMA. I also performed a factory reset on my phone and still nothing. Its frustrating a bit because i specifically bought my Galaxy S5 with Verizon so i could be on 4G LTE and now i cant get it anymore. If Verizon cant seem to figure out my problem with my phone, is this covered under the warranty? I just bought my phone in may 2014.

  • Trying to import cd, it only shows tracks, not song titles. when i try and get the titles it says im not registered for online use even though im signed in. how can i fix this?

    Im trying to import songs from a cd, but it only shows track numbers, no title of songs.when it try to get the titles it gives error code saying im not registered for online use. i am signed into my account so i dont know how to fix this.

    The "not recognized for on-line use" error is associated with the Gracenote service that iTunes uses to look up and retrieve metadata for CDs.  Some users have reported that this error occurs when trying to import from CD, subsequent to upgrading to version 12.  A number of slightly different solutions have been reported (though all of a similar nature).
    Try walking through the following steps - before starting you may have to enable hidden files and folders to be viewed - in Windows 7 / Windows Explorer select Organize > Folder and search options, then on the View tab make sure that Show hidden files, folders and drives is selected.  Without this you won't see the AppData folder in C:\Users\username\.
    Exit iTunes
    In Windows Explorer, go to the folder C:\Users\username\AppData\Roaming\Apple Computer\iTunes
    Delete the following files:
    CD Info.cidb
    com.apple.iTunes.Gracenote.plist
    Restart iTunes
    Insert a CD and see if details are now correctly retrieved from Gracenote
    If this doesn't work: 
    In iTunes, select Edit > Preferences and make a note (or take a screenshot) of your preferences settings in all relevant tabs
    Exit iTunes
    In Windows Explorer, go to the folder C:\Users\username\AppData\Roaming\Apple Computer\iTunes
    Delete the following file:iTunesPrefs.xml
    Restart iTunes
    Insert a CD and see if details are now correctly retrieved from Gracenote
    If this second procedure does work, you'll need to restore other iTunes preferences settings to those that you noted in step 1.
    If this one didn't work: 
    Exit iTunes
    Check the following folders:
    C:\Users\username\AppData\Local\Apple Computer\iTunes
    C:\Users\username\AppData\LocalLow\Apple Computer\iTunes
    Delete any copies of the following files:
    CD Info.cidb
    com.apple.iTunes.Gracenote.plist
    iTunesPrefs.xml
    Restart iTunes
    Insert a CD and see if details are now correctly retrieved from Gracenote
    Again, if this procedure does work, you'll need to restore other iTunes preferences settings to those that you noted in step 1 of the second procedure. 
    If you're still not able to retrieve CD info: 
    Exit iTunes
    In Windows, select Start > Control Panel > Programs and Features.  Find the entry for iTunes, right-click and select Repair.
    When this process has finished, restart iTunes
    Insert a CD and see if details are now correctly retrieved from Gracenote
    If none of these have worked (and almost everything I've seen suggests you should be OK by this point), you may have an issue with the installation and configuration of iTunes itself.  If you have got this far, see turingtest2's notes on Troubleshooting issues with iTunes for Windows updates for advice on how to remove and replace of all components of iTunes.

  • Everytime I try to use "send link" Firefox crashes! How can I fix this?

    Every time I click on "Send Link" to send a webpage to someone, Firefox will crash. This has only started recently, used to be able to do this. I believe the box says "Firefox has unexpectedly stopped working, then closes

    Since this all happening when using an app, you can try doing a reset.
    Hold down the home/sleep button together until you see the apple logo and then release, then wait for the phone to boot back up.

  • My cell service won't connect, how can I fix this?

    I turned it on airplane mode, then back to regular and now it won't connect....

        Oh wow! We understand the importance of being able to have service on your iPhone 5. We are hoping that things are back to normal, but if not, we want to get more details from you.
    Let's determine if there is a phone issue or a network issue. Are your calls, texts and data all affected? Where are you located?
    TamaraH_VZW
    Follow us on Twitter @VZWSupport

  • HT1212 i am attempting to restore an i pad mini but computer keeps timing out of network connection how can i fix

    Im attempting to restore ipad mini but itunes site keeps timing out how do i fix

    If you are doing it via your computer's iTunes then try temporarily turning off all your firewall and antivirus software on your computer until the download/restore has completed.

Maybe you are looking for

  • Please settle this discrepancy once and for all re: maximum ram.

    My old iMac SE DV graphite was purchased and delivered in January, 2000. The original order catalog (which I kept) claimed that it was "expandable to 512mb", as were all the 400mhz G3 slot-loading DV models in various 'flavors' including my Graphite

  • Webstart to Servlet Performance Issues

    Hi. I have a application that connects to a servlet to do database operations on a server. When it runs as either an application or an applet, the performance is great. However, when I try to deploy it with WebStart, the performance is terrible, a da

  • Standalone Logviewer does not display newly added subdirectories.

    We are running the logviewer daemon on our UNIX servers so the developers can monitor the logs.  We noticed that whenever a new subdirectory in our case a log4j log file subdirectory; the file does no show up in the logviewer until after you restart

  • Z1 compact wont turn on, three vibrations, flashing red light

    phone wont turn on, tried the red button off button, tried the power and volume button, when in charge it keeps vibrating 3 times and flashing a red light, what can I do?

  • Show size of rounded corners in Appearance palette

    Hi, I often use the Rounded Corners effect on objects, and I think it would be useful to see the size of the rounded corners in the Appearance palette. That is, it would be nice to see it automatically, without having to click on "Round Corners" to o