Downloading a File with Java
Hi
My application downloads a file from a
website.
The problem I am having is that if no internet connection is present the
program throws an exception to do with "Unable to resolve Inet Address".
If there is an internet connection present it works fine.
The behaviour I would like (and indeed had until I upgraded to WInXp
Pro) is for the application to prompt the user to connect to the
internet if no connection is present.
I have been unable to locate a method in Java that checks whether an
internet connection is present of not.
I am unsure whether the problem is with the setup of the operating
system or with my code, but if Internet Explorer or Outlook are loaded
with no internet connection present then a prompt to connect to the web
is displayed.
Any help would be much appreciated
Thanks
dear friend
u can do like this.
try {
//put your statement here
} catch(<TheException that is thrown>)
System.ot.println("connection to internet is not present");
next part of code
u can also use a finally block if u want that a
statement must be executed.hope u know syntax for that.
regards
sheetal
Similar Messages
-
Problem unzipping larger files with Java
When I extract small zip files with java it works fine. If I extract large zip files I get errors. Can anyone help me out please?
import java.io.*;
import java.util.*;
import java.net.*;
import java.util.zip.*;
public class updategrabtest
public static String filename = "";
//public static String filesave = "";
public static boolean DLtest = false, DBtest = false;
// update
public static void main(String[] args)
System.out.println("Downloading small zip");
download("small.zip"); // a few k
System.out.println("Extracting small zip");
extract("small.zip");
System.out.println("Downloading large zip");
download("large.zip"); // 1 meg
System.out.println("Extracting large zip");
extract("large.zip");
System.out.println("Finished.");
// update database
boolean maindb = false; //database wasnt updated
// download
public static void download (String filesave)
try
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new
java.net.URL("http://saveourmacs.com/update/" + filesave).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(filesave);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte data[] = new byte[1024];
while(in.read(data,0,1024)>=0)
bout.write(data);
bout.close();
in.close();
catch (Exception e)
System.out.println ("Error writing to file");
//System.exit(-1);
// extract
public static void extract(String filez)
filename = filez;
try
updategrab list = new updategrab( );
list.getZipFiles();
catch (Exception e)
e.printStackTrace();
// extract (part 2)
public static void getZipFiles()
try
//String destinationname = ".\\temp\\";
String destinationname = ".\\";
byte[] buf = new byte[1024]; //1k
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
zipinputstream = new ZipInputStream(
new FileInputStream(filename));
zipentry = zipinputstream.getNextEntry();
while (zipentry != null)
//for each entry to be extracted
String entryName = zipentry.getName();
System.out.println("entryname "+entryName);
int n;
FileOutputStream fileoutputstream;
File newFile = new File(entryName);
String directory = newFile.getParent();
if(directory == null)
if(newFile.isDirectory())
break;
fileoutputstream = new FileOutputStream(
destinationname+entryName);
while ((n = zipinputstream.read(buf, 0, 1024)) > -1)
fileoutputstream.write(buf, 0, n);
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}//while
zipinputstream.close();
catch (Exception e)
e.printStackTrace();
}In addition to the other advice, also change every instance of..
kingryanj wrote:
catch (Exception e)
System.out.println ("Error writing to file");
//System.exit(-1);
..to..
catch (Exception e)
e.printStackTrace();
}I am a big fan of the stacktrace. -
<blockquote>Locking duplicate thread.<br>
Please continue here: [/questions/815207]</blockquote><br>
if i try to download a file with any special characters in file name (e.g. File_Name.pdf), it doesn't reconvert them from the "sanitize url" process and download the file an incorrect name (e.g. File%5FName.pdf).
This is really annoying.
Thank you for your patientStart Firefox in <u>[[Safe Mode]]</u> to check if one of the extensions is causing the problem (switch to the DEFAULT theme: Firefox (Tools) > Add-ons > Appearance/Themes).
* Don't make any changes on the Safe mode start window.
* https://support.mozilla.com/kb/Safe+Mode
* [[Troubleshooting extensions and themes]] -
I can't open or save file with Java Web Start
Hi,
i can't open or save file with Java Web Start:
import java.io.*;
import java.util.*;
public class MetaDataFileCreator {
public String fileNameSpace = null;
public String fileName = null;
protected Properties file = null;
public MetaDataFileCreator(String fileNameSpace, String fileName) {
this.fileNameSpace = fileNameSpace;
this.fileName = fileName;
public void createMetaDataFile() {
try {
System.out.println("file METADATA");
ClassLoader cl = this.getClass().getClassLoader();
String nameFileMetaData = fileNameSpace + fileName + ".txt";
FileOutputStream fileOS = new FileOutputStream(cl.getResource(nameFileMetaData).getFile());
file = new Properties();
file.setProperty("aaaaa", "aaaa");
file.store(fileOS, "");
fileOS.close();
} catch (Exception e) {
System.out.println("Error writing metadata-file: " + e);
System.exit(1);
e.printStackTrace();
I have try also to open a file like this:
ClassLoader cl = this.getClass().getClassLoader();
file.load(cl.getResourceAsStream(nameFile));
also like this:
try {
fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
fss = (FileSaveService)ServiceManager.lookup("javax.jnlp.FileSaveService");
} catch (UnavailableServiceException e) {
fss = null;
fos = null;
System.out.println("Error with JNLP");
System.exit(1);
if (fss != null && fos != null) {
try {
// get a FileContents object to work with from the
// FileOpenService
FileContents fc = fos.openFileDialog(null, null);
//FileContents newfc2 = fss.saveAsFileDialog(null, null, fc);
// get the OutputStream and write the file back out
if (fc.canWrite()) {
// don't append
os = fc.getOutputStream(false);
} catch (Exception e) {
e.printStackTrace();
also like this:
File f = new File((System.getProperty("user.home")+"x.txt").toString());
FileOutputStream fileX = new FileOutputStream(f);
OutputX = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fileX, "UTF8")));
OutputX.println(....
but it doesn't work with Java Web Start.
Can someone help me?
How can I open or save file?
thank you.
SebastianoDid you specify <all-permissions/> in your JNLP file? Did you sign your code? What error are you getting?
-
How to use parameter file with java
Is it possible to use a parameter file with Java, and is there any class/method to make it easy to call and use these parameter from a text file, other than scanning the whole text file manually as we can do normally with visual basic/c++, so we can call the program with the parameter file, like java testing c:\\testing.ini
If I understand you correctly, you may be looking for a properties file. This is basically a text file that contains pairs of strings in the form:
parameter1=value1
parameter2=value2
parameter3=value3
...etc.
and the values are retrieved using the java.util.Properties class - see:
http://java.sun.com/j2se/1.3/docs/api/java/util/Properties.html
Sample use://Call chis method once, to load the props file.
//props file is called "demo.properties", and is
//in a directory that is included in the classpath
private void loadMyProperties() throws Exception
InputStream stream = getResourceAsStream("/demo.properties");
if(stream == null)
throw new Exception("stream is null!");
demoProperties = new Properties();
demoProperties.load(stream);
stream.close();
// Then you can retrieve properties in your code using:
String param3 = demoProperties.getProperty("parameter3");
//...etc -
Can't create log file with java.util.logging
Hi,
I have created a class to create a log file with java.util.logging
This class works correctly as standalone (without jdev/weblogic)
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;
public class LogDemo
private static final Logger logger = Logger.getLogger( "Logging" );
public static void main( String[] args ) throws IOException
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String dateStr = dateFormat.format(date);
String logFileName = dateStr + "SEC" + ".log";
Handler fh;
try
fh = new FileHandler(logFileName);
//fh.setFormatter(new XMLFormatter());
fh.setFormatter(new SimpleFormatter());
logger.addHandler(fh);
logger.setLevel(Level.ALL);
logger.log(Level.INFO, "Initialization log");
// force a bug
((Object)null).toString();
catch (IOException e)
logger.log( Level.WARNING, e.getMessage(), e );
catch (Exception e)
logger.log( Level.WARNING, "Exception", e);
}But when I use this class...
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;
public class TraceUtils
public static Logger logger = Logger.getLogger("log");
public static void initLogger(String ApplicationName) {
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String dateStr = dateFormat.format(date);
String logFileName = dateStr + ApplicationName + ".log";
Handler fh;
try
fh = new FileHandler(logFileName);
fh.setFormatter(new XMLFormatter());
logger.addHandler(fh);
logger.setLevel(Level.ALL);
logger.log(Level.INFO, "Initialization log");
catch (IOException e)
System.out.println(e.getMessage());
}and I call it in a backingBean, I have the message in console but the log file is not created.
TraceUtils.initLogger("SEC");why?
Thanks for your help.I have uncommented this line in logging.properties and it works.
# To also add the FileHandler, use the following line instead.
handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandlerBut I have another problem:
jdev ignore the parameters of the FileHandler method .
And it creates a general log file with anothers log files created each time I call the method logp.
So I play with these parameters
fh = new FileHandler(logFileName,true);
fh = new FileHandler(logFileName,0,1,true);
fh = new FileHandler(logFileName,10000000,1,true);without succes.
I want only one log file, how to do that? -
HT5701 Cannot download pdf files with Safari 6.0.4?
Cannot download pdf files with Safari 6.0.4
Back up all data.
Triple-click the line of text below to select it, the copy the selected text to the Clipboard (command-C):
/Library/Internet Plug-ins
In the Finder, select
Go ▹ Go to Folder
from the menu bar, or press the key combination shift-command-G. Paste into the text box that opens (command-V), then press return.
From the folder that opens, remove any items that have the letters “PDF” in the name. You may be prompted for your login password. Then quit and relaunch Safari, and test.
The "Silverlight" web plugin distributed by Microsoft can also interfere with PDF display in Safari, so you may need to remove it as well, if it's present.
If you still have the issue, repeat with this line:
~/Library/Internet Plug-ins
If you don’t like the results of this procedure, restore the items from the backup you made before you started. Relaunch Safari again. -
Executing a file with Java?
Hi,
I wanted to know how I could execute a file with java. Here are a couple scenarios - let's say I am developing an anti-spyware utility and I wanted to first write a batch file, and then create it in a folder, then run it when they click "Run". Then afterwards I want to shutdown their computer.
My Mindset:
- FileWriter to create the .bat and write the Batch commands.
- Execute the batch file.
- Execute the shutdown.exe file to reboot their PC.
So my simple question is, how can I execute a file?
Thanks!
-JoshWell here is the code I have:
try
Runtime.getRuntime().exec("cmd.exe /c test.bat");
catch(IOException e1)
//NOTHING
}Now my cmd.exe is obviously in my Windows System32 folder, and my "test.bat" file is in my C:\ root directory. So I am wondering why that wont execute. I tried a fer other things too like:
Runtime.getRuntime().exec("cmd.exe c:\test.bat");that didn't work either, because you can't have a "\" in a string...
So how can I get this thing to execute the batch file? -
Is it possible to play .rm and .wma file with java?
Hello Friends,
Please tell me,
how to play .rm and .wma file with java?
Thanks,
Harsh ModhaAs far as I know, you can not play those files.
Here you have the complete list of supported formats. Hope this helps.
http://java.sun.com/products/java-media/jmf/2.1.1/formats.html
Maybe you should try to convert from wma or rm to a supported format before attempting to play it. -
Downloading PDF file with a servlet
I'm working on a web application that dynamicaly creates a PDF file and then writes each character to the ServletOutputStream. Ideally, the browser is supposed to recognize the "application/pdf" MIME type and force the file to be downloaded (or opened from current location if the user should choose). When I test it on my local system, the file downloads but it uses the servlet as the file name. On my webserver I get the following problems.
1) On all the browsers I've tested (except Internet Explorer), the output is being printed in ASCII to the display which keeps the file from downloading. Internet Explorer is the only browser that will actually download the file.
2) When it does attempt to download the file, it is creating a file with the servlet as the name as opposed to the filename that I am assigning during creation.
I've been reading all the related posts that I could find in these Forums but haven't been able to find a solution. If anybody has any ideas, I would greatly appreciate your knowledge. Please note that I have set up MIME-mapping for the PDF extension in the WEB.XML file on my web server.
Here is some servlet code that handles the PDF creation and download:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
InputStream in = null;
ServletOutputStream out = null;
String dir = "/www/mydirectory/";
try {
// Create the PDF file and retrieve the filename
String filename = PDFCreator.main();
//Flush the response stream and then reset it for writing a PDF to the display
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename="+filename);
out = response.getOutputStream();
in = new BufferedInputStream( new FileInputStream(dir+filename));
int ch;
while ( (ch = in.read()) != -1 ) {
out.print( (char)ch );
} catch (Exception e) {
e.printStackTrace();
} finally {
if( in != null ) {
in.close();
if( out != null ) {
out.flush();
out.close();Your code looks correct.
Apparently other people too have been having problems with pdf's. These links may help you solve the problem.
http://forum.java.sun.com/thread.jsp?forum=54&thread=100793
http://forum.java.sun.com/thread.jsp?forum=33&thread=250668
http://forum.java.sun.com/thread.jsp?forum=33&thread=63282
Redirecting may not be a good idea due to url hacking. Streaming the output would be the best way to go. -
I have implemented upload and download files with uiXML
like in msg Re: How can I upload and download files with uiXML? but
it's don't work... I don't have the Errors, i don't find the file that was uploaded...
my web.xml :
<servlet>
<servlet-name>uix</servlet-name>
<servlet-class>oracle.cabo.servlet.UIXServlet</servlet-class>
<init-param>
<param-name>oracle.cabo.servlet.AbstractPageBroker</param-name>
<!-- <param-value>oracle.cabo.servlet.xml.UIXPageBroker</param-value> -->
<!-- And we'll use a custom page broker -->
<param-value>insiel.cpsg.M00.bean.UploadingPageBroker</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
testUpload.uix
<?xml version="1.0" encoding="UTF-8"?>
<page xmlns="http://xmlns.oracle.com/uix/controller">
<content>
<pageLayout xmlns="http://xmlns.oracle.com/uix/ui">
<contents>
<form name="uploadForm" usesUpload="true">
<contents>
<fileUpload name="uploadedFile"/>
<submitButton name="upload" text="Upload"/>
</contents>
</form>
</contents>
</pageLayout>
</content>
</page>
PageBroker
package insiel.cpsg.M00.bean;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import oracle.cabo.servlet.BajaContext;
import oracle.cabo.servlet.Page;
import oracle.cabo.share.util.MultipartFormItem;
import oracle.cabo.servlet.xml.UIXPageBroker;
* An extension of UIXPageBroker which stores all uploaded
* files in the temporary directory.
public class UploadingPageBroker extends UIXPageBroker {
* Override of AbstractPageBroker.doUploadFile() which saves
* all files to the temporary directory.
protected String doUploadFile(BajaContext context, Page page, MultipartFormItem item) throws IOException {
// Get the location of the file to create in the temp directory.
// Of course a real application probably wouldn't upload files to
// the temp directory - just using this contrived example to
// demonstrate basic uploading support.
File file = _getFile(context, item);
// Create a FileOutputStream. Of course, a real application would
// probably want to buffer the output
if (file != null) {
FileOutputStream out = new FileOutputStream(file);
item.writeFile(out); // Write out the file
out.close(); // Close up the output stream
// We can return a value here to add to the PageEvent
// if so desired.
return null;
// Gets the File for the item that we are uploading
private File _getFile(BajaContext context, MultipartFormItem item ) throws IOException {
String name = item.getFilename(); // Get the file name
if (name == null) return null; // If we don't have a file, bail...
// Get the path to the temporary directory
File dir = _getTempDir();
// Return the File object
return new File(dir, name);
// Returns the path to the temprary directory
private File _getTempDir() throws IOException {
// Get the temporary directory from the ServletContext
ServletConfig sConfig = getServlet().getServletConfig();
ServletContext sContext = sConfig.getServletContext();
File ff= (File) sContext.getAttribute("javax.servlet.context.tempdir");
System.out.println(ff.getAbsoluteFile());
if( ff == null ) {
throw new IOException( "Error in FileUploadFilter : No upload "+
"directory found: set an uploadDir init "+
"parameter or ensure the " +
"javax.servlet.context.tempdir directory "+
"is valid" );
return (File)sContext.getAttribute("javax.servlet.context.tempdir");
lease HELP me !!!Please stick to 1 post per question.
Refer to:
Upload and Download with uiXML (very urgent)
Jeanne -
Problem downloading ZIP file with Squid-3.0
Hi,
I have upgraded my Linux CentOS squid proxy servers to Squid version 3.0. Since then I can not download the following file it just hangs :
http://download.oracle.com/otn/java/sqldeveloper/sqldeveloper-1.5.5.59.69.zip
I dont see any error in the squid logs or on my firewall.
I can however download it on one of the older servers still running Squid version 2.6.
It is just very strange as I can download ZIP files from any other website with the upgraded servers.
Any ideas on what might cause this ?
Thanks
JHEFER
Edited by: jhefer on Nov 19, 2009 12:15 AMIf you have already interested, I found the solution. The problem is that oracle website (and probably others) uses “Vary” field in the header and squid doesn’t support this (by default). You have to download squid sources on http://www.squid-cache.org/Versions/ and compile these with “--enable-http-violations” parameter :
*./configure ‘--enable-http-violations’ ‘…’ ‘…’*
make all
make install
I hope this solution will be very useful to you.
Laurent -
Hello,
I would like to write a Java application to download some files from the Internet.
I have a basic understanding of Sockets with Perl. However, I have not done this in Java.
I would like to connect to a file on the Internet via a Socket and copy the file to my local machine.
I have browsed for tutorials on the Internet but have not found anything dealing with this (as mostly all information deals with downloading the JVM and such).
I can code it myself as I am not looking for a solution. However, I am looking for some basic pointers to get started. I was hoping someone could give me a list of classes I would need, a few urls to some nice tutorials or even some very basic code examples. Again, I just need to be pointed in the right direction to get started.
Thank you in advance!
Cheers,
ChrisWouldnt it be possible for example "protect" the
server using username and password? For example the
URL could be:
http:\\www.mywebsite.com\my_upload_page.html?password=m
password&username=myusername
or something like that??Sure; but instead of passing clear-text usernames and passwords on the URL, the usual convention is to use encrypted authentication (ranging from BASIC authentication to CERTIFICATE authentication, where the authentication is put into the HTTP request body and encrypted at some level). But it of course still requires that the server be running some special servlet/application to accept the upload requests (hence the servlet/FTP hint).
That's all I'm going to say about it; it can be far too much a topic for discussion here and I don't want to spend all that much time on it. -
Generation of Xml file with java output
Hi i m new to xml and java combination. I have a name value pair kind of output returning from java program. I want to generate the new xml file with the data. Could some one help me out in generating xml file with the data. Could anyone send me the java code that does this task.
Let me know which parser are you using currently for reading xml files so that i assist you. For now, you can refer to STAX Parser API under this link
http://java.sun.com/webservices/docs/1.6/tutorial/doc/SJSXP3.html -
Can't download a file with : in it
ok, I have a cron job on my server that does a MySQL Dump twice a day. the file output is this ( FileName_01-29-2015_15:53:11.sql.gz) when I try to download it using Dreamweaver it fails:
I can use FileZilla and download it fine so I did some testing and found that the ( : ) in the time is the problem. this i can't change on my server. is there a way to tell DW to download it anyway??
======================== error output========================
Started: 1/29/15 4:55 PM
Path was: unknown:
FileName_01-29-2015_15:53:11.sql.gz - error occurred - An FTP error occurred - cannot get FileName_01-29-2015_15:53:11.sql.gz. Access denied. The file may not exist, or there could be a permission problem.
File activity incomplete. 1 file(s) or folder(s) were not completed.
Files with errors: 1
FileName_01-29-2015_15:53:11.sql.gz
Finished: 1/29/15 4:55 PM
======================== error output========================
Using Dreamweaver CC with latest updates on Mac OS 10.10.2, connecting to server Ubuntu 12.04 LTSI think the only way you'll be able to get this with DW would be to rename the file first. Might as well use filezilla.
Maybe you are looking for
-
When I go under System Preferences-Sharing-File Sharing-Options there is an account listed called "Calender Server" that is checked. When I try to uncheck it, it asks for a password to turn it off and I don't know the password. How do I either turn t
-
Help Required in Master data Data model
Hello, May some one help me in explaining the relation with the sales org, sales office, sales group, distribution channel, division, plant, material, Customer, controlling area, profit centre and cost element. These are the info objects I have in my
-
How do I get the keyboard in the notes section of the ipad to pop up? It was working all day today and then stopped.
-
Hi, I developed an adobe form, it has 3 subwindows. Form structure is: It has 3 pages: Page 1 contains Subwindow 1. This is a fixed subform which always comes. This subfirn has 3 checkboxes. Page 1 has subform 2 also. page 2 has subform 3 page 3 has
-
NWDI Track defination for E-Commerce (crm)
Hi , we need to set up newtrack for our e-commerce system in NWDI .In the document it says .. 1) "Copy original Software Component from SAP-SHRAPP to CUSTCRMPRJ Change Context Root Exclude SAP-SHRAPP from deployment " Q:What does it mean? 2) duri