Download a file over a network in J2ME midlet

By: Eriq Tan Emailed: 1730 times Printed: 2344 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

This sample code can be used to download and view a file over a network in a TextBox component Through an httpConnection,

Important Points:

1)   One benefit of using an HttpConnection (as compared to InputStream or StreamConnection) is the availability of a method to check for the length of the remote data. The data can then be read in one fell-swoop, in contrast to reading one character/byte at a time.

2)      Before leaving the viewFile() method, check to the status of the input stream and the httpConnection, and close if necessary. 

3)   This example is written for version 1.0.3 of MIDP and CLDC

 

Java Code:

/*--------------------------------------------------
* FileViewer.java
*
* Download and view a file over a network 
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

public class FileViewer extends MIDlet implements CommandListener
{
  private Display display;	    // Reference to Display object
  private TextBox tbViewer;  // View file contents in a textbox
  private Command cmView;    // Command to view file
  private Command cmExit;    // Command to exit
  private String url = "http://www.corej2me.com/midpbook_v1e1/scratch/fileViewer.hlp";  

  public FileViewer()
  { 
    display = Display.getDisplay(this);
    
    // Define commands
    cmView = new Command("View", Command.SCREEN, 2);
    cmExit = new Command("Exit", Command.EXIT, 1);

    tbViewer = new TextBox("Viewer", "", 250, TextField.ANY);
    tbViewer.addCommand(cmView);
    tbViewer.addCommand(cmExit);
    tbViewer.setCommandListener(this);    
  }

  public void startApp()
  {
    display.setCurrent(tbViewer);
  }    

  private void viewFile() throws IOException
  {
    HttpConnection http = null;
    InputStream iStrm = null;
    
    try
    {
      // Create the connection
      http = (HttpConnection) Connector.open(url);
      
      //----------------
      // Client Request
      //----------------
      // 1) Send request method
      http.setRequestMethod(HttpConnection.GET);
      
      // 2) Send header information (this header is optional)
      http.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
      
      // 3) Send body/data - No data for this request
      
      //----------------
      // Server Response
      //----------------
      // 1) Get status Line
      System.out.println("Msg: " + http.getResponseMessage());                  
      System.out.println("Code: " + http.getResponseCode());                
      
      // 2) Get header information 
      if (http.getResponseCode() == HttpConnection.HTTP_OK)
      {
        // 3) Get data (show the file contents)
        iStrm = http.openInputStream();
        int length = (int) http.getLength();
        if (length > 0)
        {
          byte serverData[] = new byte[length];
          iStrm.read(serverData);
          tbViewer.setString(new String(serverData));
        }
      }
    }
    finally
    {
      // Clean up
      if (iStrm != null)
        iStrm.close();
      if (http != null)
        http.close();
    }
  }

  public void pauseApp()
  { }

  public void destroyApp(boolean unconditional)
  { }

  public void commandAction(Command c, Displayable s)
  {
    if (c == cmView)
    {
      try
      {
        viewFile();
      }
      catch (Exception e)
      {
        System.out.println(e.toString());
      }
    }
    else if (c == cmExit)
    {
      destroyApp(false);
      notifyDestroyed();
    }	
  }
}

J2ME Home | All J2ME Tutorials | Latest J2ME Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(9)


1. View Comment

It works like a charm. Thanks a lot.

View Tutorial          By: Balram at 2008-08-22 21:18:44
2. View Comment

when i trying to build the above program it is giving warning on my console like
"To avoid potential deadlock, operations that may block, such as
networking, should be performed in a different thread than the
commandAction() handler."
and also giving text exception on my emulator like "is it ok to use airtime?"
why this is comming please suggest me i need it urgent.
thanx in advance


View Tutorial          By: bhagyalaxmi at 2008-10-10 23:45:45
3. View Comment

when i trying this code . i am getting this error

java.lang.NoClassDefFoundError: com/sun/kvem/midp/MIDP$KVMInterface
at com.sun.kvem.midp.MIDP.run(Unknown Source)
at com.sun.kvem.environment.EmulatorInvoker.runEmulatorImpl(Unknown Source)
at com.sun.kvem.environment.EmulatorInvoker.runEmulatorSameVM(Unknown Source)
at com.sun.kvem.environment.EmulatorInvoker.runEmulator(Unknown Source)
at com.sun.kvem.environment.ProfileEnvironment$KVMThread.runEmulator(Unknown Source)
at com.sun.kvem.environment.ProfileEnvironment$KVMThread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: com.sun.kvem.midp.MIDP$KVMInterface
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 6 more
Caused by: java.io.IOException: unexpected EOF
at sun.misc.Resource.getBytes(Resource.java:103)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:256)
at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
... 11 more


View Tutorial          By: sharath at 2010-04-06 00:58:29
4. View Comment

Cool! Downloading the whole file with the HttpConnection length method. Nice!

View Tutorial          By: Luddite at 2010-06-26 12:26:26
5. View Comment

Can you mail me the compiled files, Please. Thank u.

View Tutorial          By: raghav at 2010-09-14 21:23:17
6. View Comment

samples

View Tutorial          By: kamlesh at 2010-11-18 03:33:09
7. View Comment

Hi, I second that Raghav, kindly can u email me a compiled files as well, am doin a research about remote monitoring and your sample helped me alot. Appreciate it.

View Tutorial          By: SAM at 2011-03-06 05:03:09
8. View Comment

how to download suport to my phone
send me aplication to downloaded j2me code and java midlet
please....


View Tutorial          By: dede.mouljadie at 2012-04-28 09:39:21
9. View Comment

Whe I compiled the above code, it sends me to the "Viewer" and when I select "View", nothing happens. It is just the blank screen. Any help?

View Tutorial          By: Koo Larbi at 2014-08-02 22:32:05

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Eriq Tan
Download a file over a network in J2ME midlet

More Tutorials in J2ME
Code sample to Send SMS from a J2ME application.
Adding your own Application icon for your J2ME application (jar file)
Play a multimedia file in J2ME Program (Audio/Video) using MMAPI
Datagrams in J2ME (UDP Programming sample)
Client Server in J2ME (Socket Programming sample)
Using HttpConnection in J2ME (Retrieve web content from a website to a phone)
Using HTTP vs UDP vs Socket in J2ME
RMSCookieConnector - Using Cookies in J2ME
POST UTF-8 encoded data to the server in J2ME
lists, forms, choices, gauges, text fields, text boxes in J2ME
Using List to create a Menu and Menu items in J2ME
Using alerts and tickers in J2ME
J2ME Canvas sample to show games programming in J2ME
Timer and TimerTask example in J2ME
List of GPRS Access points for all countries

More Latest News
Most Viewed Articles (in J2ME )
Sample Java program shows how to Read a file over a network using J2ME midlet
Download a file over a network in J2ME midlet
List of GPRS Access points for all countries
Using List to create a Menu and Menu items in J2ME
Code sample to Send SMS from a J2ME application.
POST UTF-8 encoded data to the server in J2ME
Adding your own Application icon for your J2ME application (jar file)
'LINK.EXE' is not recognized as an internal or ext
Sample J2ME code that shows various functionality of RMS.
Your first J2ME program and a midlet lifecycle explained.
How to get the CLDC and MIDP version from a J2ME program
Gauge sample program in J2ME
translate() Sample program in J2ME
RMS Basics in J2ME
J2ME Canvas sample to show games programming in J2ME
Most Emailed Articles (in J2ME)
Sample program to draw a arc in J2ME
translate() Sample program in J2ME
Types of configurations in J2ME
Timer and TimerTask example in J2ME
Adding your own Application icon for your J2ME application (jar file)
What is J2ME?
Download a file over a network in J2ME midlet
How to load J2ME applications to the IDEN handsets
Y.S. Sun Green Building Research Center
'LINK.EXE' is not recognized as an internal or ext
Sample Java program shows how to Read a file over a network using J2ME midlet
Sample J2ME code that shows various functionality of RMS.
A sample J2ME midlet that shows an example of using a Timer and a TimerTask.
GUI components and menu based J2ME Applications.
Your first J2ME program and a midlet lifecycle explained.