0

Hi I am trying to write some code in my program so I can grab a file from the internet but it seems that is not working. Can someone give me some advice please ? Here is my code. In this case I try to download an mp3 file from the last.fm website, my code runs perfectly fine but when I open my downloads directory the file is not there. Any idea ?

  public class download {

  public static void main(String[] args) throws IOException {

     String fileName = "Death Grips - Get Got.mp3"; 
     URL link = new URL("http://www.last.fm/music/+free-music-downloads"); 

     InputStream in = new BufferedInputStream(link.openStream());
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     byte[] buf = new byte[1024];
     int n = 0;
     while (-1!=(n=in.read(buf)))
     {
        out.write(buf, 0, n);
     }
     out.close();
     in.close();
     byte[] response = out.toByteArray();

     FileOutputStream fos = new FileOutputStream(fileName);
     fos.write(response);
     fos.close();


     System.out.println("Finished");

}

}

3
  • 3
    Why do you think it should be in your downloads directory? Commented Apr 23, 2014 at 15:26
  • I guess that is the default location for downloading a file ? or do I have to specify where the file is going to be stored ? Commented Apr 23, 2014 at 15:28
  • Ideally, you would specify a full path. If you don't, you get the behavior explained in Jonathan's answer. Commented Apr 23, 2014 at 15:28

1 Answer 1

2

Every executing program has a current working directory. Often times, it is the directory where the executable lives (if it was launched in a "normal" way).

Since you didn't specify a path (in fileName), the file will be saved with that name in the current working directory.

If you want the file to be saved in your downloads directory, specify the full path. E.g.

String fileName = "C:\\Users\\YOUR_USERNAME\\Downloads\\Death Grips - Get Got.mp3"; 

Note how I've escaped the backslashes. Also note that there are methods for joining paths in Java. There is a way to get the current working directory in Java.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, thank you for your advice. How could I specify the directory that I want the file to be stored ? many thanks
Hmmm I just used your code in order to specify the directory and it throws me an error saying that the system cannot find the specified directory. Any advice ?
@user3449550 Is now username on windows Bob?
Yeah that was the problem, my bad I had to change it to my username Many thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.