I have a URL, http://www.skype.com/en/download-skype/skype-for-windows/downloading/. If I run this URL in Chrome the EXE file of Skype starts downloading. However if I write the code to download the file I am not able to do so. Here is my code:
public static void saveFile(URL url, String file) throws IOException {
System.out.println("opening connection");
InputStream in = url.openStream();
FileOutputStream fos = new FileOutputStream(new File(file));
System.out.println("Reading file...");
int length = -1;
byte[] buffer = new byte[1024]; // Buffer for portion of data from
// Connection
while ((length = in.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
fos.close();
in.close();
System.out.println("File was downloaded");
}
public static void main(String args[])
{
try
{
URL url = new URL("http://www.skype.com/en/download-skype/skype-for-windows/downloading/");
String fileName = "C:/SETUP/skype.exe";
saveFile(url, fileName);
}
catch(IOException e)
{
e.printStackTrace();
}
}
You're pointing to the wrong URL. At http://www.skype.com/en/download-skype/skype-for-windows/downloading/ you only get the HTML page where you're ABLE to download the exe.
The direct URL that refers to the exe is: http://get.skype.com/go/getskype
Related
I have a URL, http://www.skype.com/en/download-skype/skype-for-windows/downloading/. If I run this URL in Chrome the EXE file of Skype starts downloading. However if I write the code to download the file I am not able to do so. Here is my code:
public static void saveFile(URL url, String file) throws IOException {
System.out.println("opening connection");
InputStream in = url.openStream();
FileOutputStream fos = new FileOutputStream(new File(file));
System.out.println("Reading file...");
int length = -1;
byte[] buffer = new byte[1024]; // Buffer for portion of data from
// Connection
while ((length = in.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
fos.close();
in.close();
System.out.println("File was downloaded");
}
public static void main(String args[])
{
try
{
URL url = new URL("http://www.skype.com/en/download-skype/skype-for-windows/downloading/");
String fileName = "C:/SETUP/skype.exe";
saveFile(url, fileName);
}
catch(IOException e)
{
e.printStackTrace();
}
}
You're pointing to the wrong URL. At http://www.skype.com/en/download-skype/skype-for-windows/downloading/ you only get the HTML page where you're ABLE to download the exe.
The direct URL that refers to the exe is: http://get.skype.com/go/getskype
I have a URL i.e http://downloadplugins.verify.com/Windows/SubAngle.exe .
If I paste it on the tab and press enter then the file (SubAngle.exe) is getting downloaded and saved in the download folder. This is a manual process. But it can be done with java code.
I wrote the code for getting the absolute path with the help of the file name i.e SubAngle.exe.
Requirement:- With the help of the URL file gets downloaded,Verify the file has been downloaded and returns the absolute path of the file.
where locfile is "http://downloadplugins.verify.com/Windows/SubAngle.exe"
public String downloadAndVerifyFile(String locfile) {
File fileLocation = new File(locfile);
File fileLocation1 = new File(fileLocation.getName());
String fileLocationPath = null;
if(fileLocation.exists()){
fileLocationPath = fileLocation1.getAbsolutePath();
}
else{
throw new FileNotFoundException("File with name "+locFile+" may not exits at the location");
}
return fileLocationPath;
}
easy and general function that im using:
import org.apache.commons.io.FileUtils;
public static void downLoadFile(String fromFile, String toFile) throws MalformedURLException, IOException {
try {
FileUtils.copyURLToFile(new URL(fromFile), new File(toFile), 60000, 60000);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("exception on: downLoadFile() function: " + e.getMessage());
}
}
Instead of writing this huge code, go for Apache's commons.io
Try this:
URL ipURL = new URL("inputURL");
File opFile = new File("outputFile");
FileUtils.copyURLToFile(ipURL, opFile);
Code to DownloadFile from URL
import java.net.*;
import java.io.*;
public class DownloadFile {
public static void main(String[] args) throws IOException {
InputStream in = null;
FileOutputStream out = null;
try {
// URL("http://downloadplugins.verify.com/Windows/SubAngle.exe");
System.out.println("Starting download");
long t1 = System.currentTimeMillis();
URL url = new URL(args[0]);
// Open the input and out files for the streams
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
in = conn.getInputStream();
out = new FileOutputStream("YourFile.exe");
// Read data into buffer and then write to the output file
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
long t2 = System.currentTimeMillis();
System.out.println("Time for download & save file in millis:"+(t2-t1));
} catch (Exception e) {
// Display or throw the error
System.out.println("Erorr while execting the program: "
+ e.getMessage());
} finally {
// Close the resources correctly
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Configure the value of fileName properly to know where the file is getting stored.
Source: http://www.devmanuals.com/tutorials/java/corejava/files/java-read-large-file-efficiently.html
The source was modified to replace local file with http URL
Output:
java DownloadFile http://download.springsource.com/release/TOOLS/update/3.7.1.RELEASE/e4.5/springsource-tool-suite-3.7.1.RELEASE-e4.5.1-updatesite.zip
Starting download
Time for download & save file in millis:100184
I am working on an applet that records voice and uploads to a servlet.
Here is the code of the upload thread in the applet
class uploadThread extends Thread {
#Override
public void run() {
try {
//Preparing the file to send
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
File file = File.createTempFile("uploded", ".wav");
byte audio[] = out.toByteArray();
InputStream input = new ByteArrayInputStream(audio);
final AudioFormat format = getFormat();
final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize());
AudioSystem.write(ais, fileType, file);
//uploading to servlet
FileInputStream in = new FileInputStream(fileToSend);
byte[] buf = new byte[1024];
int bytesread = 0;
String toservlet = "http://localhost:8080/Servlet/upload";
URL servleturl = new URL(toservlet);
URLConnection servletconnection = servleturl.openConnection();
servletconnection.setDoInput(true);
servletconnection.setDoOutput(true);
servletconnection.setUseCaches(false);
servletconnection.setDefaultUseCaches(false);
DataOutputStream out = new DataOutputStream(servletconnection.getOutputStream());
while ((bytesread = in.read(buf)) > -1) {
out.write(buf, 0, bytesread);
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error during upload");
}
}
}//End of inner class uploadThread
Here is the code of the grab file method in the servlet:
java.io.DataInputStream dis = null;
try {
int fileLength = Integer.valueOf(request.getParameter("fileLength"));
String fileName = request.getParameter("fileName");
dis = new java.io.DataInputStream(request.getInputStream());
byte[] buffer = new byte[fileLength];
dis.readFully(buffer);
dis.close();
File cibleServeur = new File("/Users/nebrass/Desktop/" + fileName);
FileOutputStream fos = new FileOutputStream(cibleServeur);
fos.write(buffer);
fos.close();
} catch (IOException ex) {
Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
dis.close();
} catch (Exception ex) {
Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
I have created a certificate with the keytool. And i have signed the JAR of the applet.
I have added the applet to the jsp file and it is working, and have the all permissions (I tried to save a file on a desktop using the applet)
Update: The problem is that the file is not sent, and when i try to debug the servlet, it is not invoked by the the applet.
Please help
That's not how it works. You've just opened a URLConnection and wrote to the output stream. That way you're assuming something like a socket connection, but here we need more of a HttpUrlConnection and then a request-parameter and a multi-part request.
Google Search
Google found lots of solutions, but for the completeness of the answer, I'm adding one below :
https://stackoverflow.com/a/11826317/566092
You want up upload a file from the server to the user desktop?
I doubt this will be allowed, for obvious security reasons.
Why don't you just call the servlet directly from the browser? And "save as" the file?
Here is an exemple on how to send a file (any type) from a servlet.
protected void doPost(
...
response.setContentType("your type "); // example: image/jpeg, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/octet-stream
response.setHeader("Content-Disposition","attachment; filename=\"your_filename\"");
File uploadedFile = new File("/your_file_folde/your_file_name");
if (uploadedFile.exists()){
FileUtils.copyFile(uploadedFile, response.getOutputStream());
}
else { // Error message
}
....
}
I've create this function...
void DownloadFromDatabase() throws IOException {
URL website = new URL("http://theurlofmywebsite.org/databases/record_file.txt");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("record_file.txt");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
... and I call it when I click a button as you can see here.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
DownloadFromDatabase();
} catch (IOException ex) {
Logger.getLogger(xGrep.class.getName()).log(Level.SEVERE, null, ex);
}
}
When I click the button, DownloadFromDatabase(); is called but I don't see the file record_file.txt on my desktop. Do you know why?
This code is not the best, but I've made a test on my computer and it works. It downloads a text file with 500 lines in 2 seconds.
void DownloadFromDatabase() throws MalformedURLException, IOException {
URLConnection conn = new URL("your_url_here").openConnection();
InputStream is = conn.getInputStream();
OutputStream outstream = new FileOutputStream(new File("filename.txt"));
byte[] buffer = new byte[4096];
int len;
while ((len = is.read(buffer)) > 0) {
outstream.write(buffer, 0, len);
}
outstream.close();
}
I've named it DownloadFromDatabase() so you only have to copy/paste this code instead of yours. Also, pay attention with the exceptions.
I would like to send file from client to server and be able do it again in the future.
So my client connect to server and upload file, ok - it works but it hangs at the end..
so here is my code in client, the server side is quite similar.
private void SenderFile(File file) {
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = socket.getOutputStream();
IoUtil.copy(fis, os);
} catch (Exception ex) {
ex.printStackTrace();
}
}
IoUtils found on Stack :)
public static class IoUtil {
private final static int bufferSize = 8192;
public static void copy(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[bufferSize];
int read;
while ((read = in.read(buffer, 0, bufferSize)) != -1) {
out.write(buffer, 0, read);
}
out.flush();
}
}
Explanation: my client has a socket connected to server, and I send any file to him.
My server download it but hangs at the end because he is listening for more infromation.
If I choose another file, my server will download new data to the existing one.
How could I upload any file to server, make my server work on and be able download another one file properly?
ps. If I add to ioutil.copy at the end of function out.close my server will work on but the connection will be lost. I do not know what to do :{
After update:
Client side:
private void SenderFile(File file) {
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = socket.getOutputStream();
DataOutputStream wrapper = new DataOutputStream(os);
wrapper.writeLong(file.length());
IoUtil.copy(fis, wrapper);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Server side (thread listening for any message from client):
public void run() {
String msg;
File newfile;
try {
//Nothing special code here
while ((msg = reader.readLine()) != null) {
String[] message = msg.split("\\|");
if (message[0].equals("file")) {//file|filename|size
String filename = message[1];
//int filesize = Integer.parseInt(message[2]);
newfile = new File("server" + filename);
InputStream is = socket.getInputStream();
OutputStream os = new FileOutputStream(newfile);
DataInputStream wrapper = new DataInputStream(is);
long fileSize = wrapper.readLong();
byte[] fileData = new byte[(int) fileSize];
is.read(fileData, 0, (int) fileSize);
os.write(fileData, 0, (int) fileSize);
System.out.println("Downloaded file");
} else
//Nothing special here too
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Ok, now I can download file - still once, another one is downloaded but unable to read. For example, second time I want send by client a file.png. I got it on server, but this file is not possible to view.
Thanks in advance :)
You need to make your server able to differentiate files. The easiest way is to tell in advance how many bytes the receiving end should expect for a single file; this way, it knows when to stop reading and wait for another one.
This is what the SenderFile method could look like:
private void SenderFile(File file)
{
try
{
FileInputStream fis = new FileInputStream(file);
OutputStream os = socket.getOutputStream();
DataOutputStream wrapper = new DataOutputStream(os);
wrapper.writeLong(file.length());
IoUtil.copy(fis, wrapper);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
And this is what the ReceiveFile method could look like:
// the signature of the method is complete speculation, adapt it to your needs
private void ReceiveFile(File file)
{
FileOutputStream fos = new File(file);
InputStream is = socket.getInputStream();
DataInputStream wrapper = new DataInputStream(is);
// will not work for very big files, adapt to your needs too
long fileSize = wrapper.readLong();
byte[] fileData = new byte[fileSize];
is.read(fileData, 0, fileSize);
fos.write(fileData, 0, fileSize);
}
Then don't close the socket.