Pergunta

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");

}

}

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top