Static variable behaviour in memory

Hi,
My question is :
When you compile a java code, does the static variable gets the memory allocated while creating the byte code or is it on run time that a static variable gets the memory allocation and then it is shared for all instances.
Thanks
Melvyn.

Good !!! I expected this question from you.
Instantiation and Initialization are different.
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
1) T is a class and an instance of T is created.
2) T is a class and a static method declared by T is invoked.
3) A static field declared by T is assigned.
4) A static field declared by T is used and the reference to the
field is not a compile-time constant. References to
compile-time constants must be resolved at compile time to
a copy of the compile-time constant value, so uses of such a
field never cause initialization.
Regards
Raghu

Similar Messages

  • Declaring static variable to save memory, memory cost of link

    If I have plenty of objects of the same class and they have a field that is the same for all objects, do I save memory by declaring it 'static'?
    How much memory is used by an object to store a link that points to another object?
    /Carlis

    Ok!
    I am making a map for a computer game, and it has plenty of Towns. Now, every object of type 'Town' has a list with different Tribes
    String[] Tribes= {"Roman", "Teuton", "Gaul"};
    This list is identical for all objects of type 'Town'.
    Now, if I declare it to be static like this;
    static String[] Tribes={...};
    Does this save memory? If I understand this correctly, the 'static' keyword means that the 'String[] Tribes' is only stored once rather than in every object of type 'Town'.

  • How can I write an instance of a class in a static variable

    Hi !
    I have an instance of a class
    Devisen dev = new Devisen();
    In an other class I have a static method and I need there the content of some variables from dev.
    public static void abc()
    { String text=dev.textfield.getText()
    I get the errormessage, that the I cannot use the Not-static variable dev in a static variable.
    I understand that I cannot reference to the class Devisen because Devisen is not static I so I had to reference to an instance. But an instance is the same as a class with static methodes. (I think so)
    Is there a possibility, if I am in a static method, to call the content of a JTextField of an instance of a class ?
    Thank you Wolfgang

    Hallo, here is more code for my problem:
    class Login {
       Devisen dev=new Devisen();
    class Devisen {
       JTextField field2;
       if (!Check.check_field2()) return; // if value not okay than return
    class Check {
       public static void check_field2()
         HOW TO GET THE CONTENT OF field2 HERE ?
    One solution ist to give the instance to the static function, with the keyword "this"
    if (!Check.check_field2(this)) return;and get the instance
    public static void check_field2(Devisen dev)BUT is that a problem for memory to give every method an instance of the class ? I have 50 fields to control and I dont want do give every check_method an instance of Devisen, if this is a problem for performance.
    Or do I only give the place where the existing instance is.
    Hmm...?
    Thank you Wolfgang

  • Equivalent of visual Basic static variable in LabVIEW

    Hi all!
    I am doing a project where I am counting the values. After i Close/Stop the program I want the value to be intact and continue with the last value.
    I know this in Visual Basic. By using the Static variable we can retain the value even we close the program.
    Kindly help..
    Srikanth Chilivery,
    Solved!
    Go to Solution.

    I have trouble believing that a static variable retains its value after the program is terminated.  Once the program is released from memory, that static variable is gone.  If you want to retain a value between closing and opening an application, you have to save it to disk in some way.
    Are you working exclusively in the LabVIEW IDE or are you running EXEs?  It sounds like you probably just want to use a Functional Global Variable/Action Engine.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • (JC) static variable and derived object

    Hi there!
    It is glad to know you from Java Card Forum. Can I ask for your help on the following question?
    It is about static variable. The following is my sample code:
    ========================================
    package com.Test01;
    import javacard.framework.*;
    import javacard.security.*;
    import javacardx.crypto.Cipher;
    public class Test01 extends Applet {
    OwnerPIN Pin;
    static DESKey[] keys;
    protected Test01(byte[] buffer, short offset, byte length) {
    keys = new DESKey[4];
    length = 0;
    while (length < 4) {
    keys[length] = (DESKey)KeyBuilder.buildKey((byte)3, (short)0x80, false);
    length = (byte)(length + 1);
    public static void install(byte buffer[], short offset, byte length) {
    new Test01(buffer, offset, length);
    ===========================================================
    If there are two instances, A and B, created in the package.
    My issues:
    1. Are keys[0]~ keys [3] kept while B is deleted?
    2. Does each instance have itsown object while "keys[length] = (DESKey)KeyBuilder.buildKey((byte)3, (short)0x80, false);"? or they share the same object?
    3. follow item 2, if A and B share the same object, is the object kept while B is deleted? Where can I get the information in Sun's spec?
    Thank you very much.
    Best regards,
    kantie

    Thanks a lot. You mean that keys variable will be removed while instance B deleted, right? I think the idea of database applet is very good, but I can't force applet provider the way of their implementations : )
    I still got question, does it get no use to set the keys variable to be "static"? So that I can keep it to other instances, if applied.
    And I think that any object derived under the static variable shall be kept, until the package is deleted.
    For example, if you declare a static pointer, and it points to an object newed by the instance at the first time. We say every instances (A and B) of this package (PckM) share this same static pointer and this same object, right? There are two situations:
    1. if this referred object is removed when B is deleted, so the memory of this object will be released. Then user might create an instace C of another package (PckN), and instance C new its objects just overlapping on the released memory. In this case, it will cause instance A to be crashed, because its static pointer has been referred to illeagle address.
    2. if this referred object is kept when B is deleted, then instance C will new its objects in other free memory. In this case, instance A will work well, because its static pointer still refers to correct object.
    What do you think? Am I missing any concepts?
    Thank you for your great opinions.
    Best regards,
    kantie

  • Static Variable Life Span

    Hi,
    I am trying to cache some data in to a static hashtable variable from database. But when I run my test program twice in dos window, I do not see that static variable's value. Do static variables are lost if the program exits?
    How can I keep a static variable keep its value? (may be using a infinite thread loop keep program alive)
    Any Ideas, suggestions. Thanks in advance

    if you run it twice in a dos window if you do that in the same window that means your first run has finished. And that your Object doesn't exist anymore in the memory.
    Static Variables are accessible as long as you stay within the same JVM and as long as the application where those static variables are created still exists...
    Then program X stops, all the static variables from program X won't be alive anymore in the JVM.
    Stronger is that is the only program running in the JVM then i believe the JVM is exited to.
    greetings

  • Local static variable not unique between dylib, Xcode 4.4.1 bug?

    I am wondering if this is a Xcode bug or it is the way the c++ standart is.
    I would expect to  see 1 in the console but i see 0.
    Anybody know why? Here is the code
    In one dylib I have
    // Header file
    class Foo {
       int i_ = 0;
       Foo(const Foo&) = delete;
       Foo& operator= (Foo) = delete;
       Foo()
    public:
       void inc()
          ++i_;
       int geti()
          return i_;
       static Foo& get()
          static Foo instance_;
          return instance_;
       Foo( Foo&&) = default;
       Foo& operator= (Foo&&) = default;
    int initialize()
       Foo::get().inc();
       return 10;
    class Bar
       static int b_;
    // cpp file
    #include "ClassLocalStatic.h"
    int Bar::b_ = initialize();
    and in my application project i have
    // main.cpp
    #include <iostream>
    #include "ClassLocalstatic.h"
    int main(int argc, const char * argv[])
       std::cout << Foo::get().geti();
       return 0;
    Thanks

    thanks for your answer, You are right there is 2 foo singleton at different memory addresses.
    I didn't think about when the dylib was loaded. I can't even tell when it is loaded. But I know if i but breaks point I break in the initialize function before breaking in main, but that might be because of this actual setup. So when does a dylib will be loaded? At the first call a program sees that need the dylib?
    Here I'explain why it is done this way. My Singleton is a UnitTestRegistry, the Bar class is a UnitTest class and the static variable b_ is a class containing metadata info on the unit test.
    I have a macro to define the unit test it is called Make_UnitTest()
    So in a cpp I do
    Make_UnitTest(MyTest)
         // Test Stuff
    The macro will get expanded to
    class MyTest_UnitTest: public UnitTestBase
         static UniTestMetaData b_;
         virtual void executeTest();
    int MyTest_UnitTest::b_ = initializeAndRegisterUnitTest("MyTest_UnitTest", factoryFunction);
    MyTest_UnitTest::executeTest()
    // Test Stuff
    And in the function initializeAndRegisterUnitTest I call the getInstance of the unit test  registry. This way my unit test are registred at loading time of the program/dll. If you know a better way to automatically register (i know it cuold be manual but i find it too cumbersome), but it wont fix the problem which is that I have two intance of my singleton because the function is inline in a header.
    Well this behavior is surprising to me, I didn't know it would do this. But hey it is good to learn right!
    Just to make it clear there is no real global!! The singleton is like a global but it is not completly one and the b_ is certainly not global it is a class static memeber...

  • Slow performance when multiple threads access static variable

    Originally, I was trying to keep track of the number of function calls for a specific function that was called across many threads. I initially implemented this by incrementing a static variable, and noticed some pretty horrible performance. Does anyone have an ideas?
    (I know this code is "incorrect" since increments are not atomic, even with a volatile keyword)
    Essentially, I'm running two threads that try to increment a variable a billion times each. The first time through, they increment a shared static variable. As expected, the result is wrong 1339999601 instead of 2 billion, but the funny thing is it takes about 14 seconds. Now, the second time through, they increment a local variable and add it to the static variable at the end. This runs correctly (assuming the final increment doesn't interleave which is highly unprobable) and runs in about a second.
    Why the performance hit? I'm not even using volatile (just for refernce if I make the variable volatile runtime hits about 30 seconds)
    Again I realize this code is incorrect, this is purely an interesting side-expirement.
    package gui;
    public class SlowExample implements Runnable
         public static void main(String[] args)
              SlowExample se1 = new SlowExample(1, true);
              SlowExample se2 = new SlowExample(2, true);
              Thread t1 = new Thread(se1);
              Thread t2 = new Thread(se2);
              try
                   long time = System.nanoTime();
                   t1.start();
                   t2.start();
                   t1.join();
                   t2.join();
                   time = System.nanoTime() - time;
                   System.out.println(count + " - " + time/1000000000.0);
                   Thread.sleep(100);
              catch (InterruptedException e)
                   e.printStackTrace();
              count = 0;
              se1 = new SlowExample(1, false);
              se2 = new SlowExample(2, false);
              t1 = new Thread(se1);
              t2 = new Thread(se2);
              try
                   long time = System.nanoTime();
                   t1.start();
                   t2.start();
                   t1.join();
                   t2.join();
                   time = System.nanoTime() - time;
                   System.out.println(count + " - " + time/1000000000.0);
              catch (InterruptedException e)
                   e.printStackTrace();
               * Results:
               * 1339999601 - 14.25520115
               * 2000000000 - 1.102497384
         private static int count = 0;
         public int ID;
         boolean loopType;
         public SlowExample(int ID, boolean loopType)
              this.ID = ID;
              this.loopType = loopType;
         public void run()
              if (loopType)
                   //billion times
                   for (int a=0;a<1000000000;a++)
                        count++;
              else
                   int count1 = 0;
                   //billion times
                   for (int a=0;a<1000000000;a++)
                        count1++;
                   count += count1;
    }

    Peter__Lawrey wrote:
    Your computer has different types of memory
    - registers
    - level 1 cache
    - level 2 cache
    - main memory.
    - non CPU local main memory (if you have multiple CPUs with their own memory banks)
    These memory types have different speeds. Depending on how you use a variable affects which memory it is placed in.Plus you have the hotspot compiler kicking in sometime during the run. In other words for some time the VM is interpreting the code and then all of a sudden its compiled and executing the code compiled. Reliable micro benchmarking in java is not easy. See [Robust Java benchmarking, Part 1: Issues|http://www.ibm.com/developerworks/java/library/j-benchmark1.html]

  • A basic question about static variables and methods

    What would be the effects if I declare lots of static variables and static methods in my class?
    Would my program run faster?
    Would the class take more memory spaces? (If so, how do I estimate an appropriate number of variabls and methods to be declared static?)
    Thank you @_@

    when you declare a static var the var isn't created for every instance of the class, it just "live" in the class
    when you declare a static method is the same, so if you have:
    class MyClass
    static int myMethod()
    //Method work
    you dont need to have a instance of the class to call myMethod, you can do such things like this.
    int value = Myclass.myMethod();
    if myMethod isn't static you can't do this.. so, if
    class MyClass
    int myMethod()
    //Method work
    you CAN'T call
    int value = MyClass.myMethod();
    instead, you have to write
    MyClass m;
    m = new MyClass();
    value = m.myMethod();

  • When is Static variables memeory freed ?

    When is the memory used by static variables freed by the GC?

    When is the memory used by static variables freed by
    the GC?Are you talking about the variables or the objects they point to?
    class Foo {
      static Bar bar = new Bar();
      static void relaseBar () {
        bar = null;
    } The first call to releaseBar() makes the Bar object eligible for GC, so the space it occupies could be freed at any point, or never--it's totally up to the whims of GC.
    The space taken up by he bar reference variable, which is NOT the same as the object--will be eligible for GC only if and when the class is unloaded. Like anything that becomes eligible for GC, the memory isn't explicitly freed until GC runs, which is not very predictable, and my never happen at all. For most purposes, however, you can effectively consider memory "freed" at the point when it become eligible for GC.

  • Error on compile - non-static variable can not be referencedfrom static con

    Error on compile happening with addButton?
    Thanks
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JFrame;
    public class Log implements ActionListener {
    JButton addButton;
    public static void addComponentsToPane(Container pane) {
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
         c.gridy = 3;
    c.gridx = 0;
         JLabel callsignLabel= new JLabel("Callsign");
    pane.add(callsignLabel, c);
         c.gridy = 3;
    c.gridx = 1;
         JLabel nameLabel= new JLabel("Name");
    pane.add(nameLabel, c);
         c.gridy = 3;
    c.gridx = 2;
         JLabel timeLabel= new JLabel("Time");
    pane.add(timeLabel, c);
         c.gridy = 3;
    c.gridx = 3;
         JLabel dateLabel= new JLabel("Date");
    pane.add(dateLabel, c);
         c.gridy = 3;
    c.gridx = 4;
         JLabel frequencyLabel= new JLabel("Freq ");
    pane.add(frequencyLabel, c);
         c.gridy = 3;
    c.gridx = 5;
         JLabel locationLabel = new JLabel("Country/State");
    pane.add(locationLabel, c);
    c.gridy = 5;
    c.gridx = 0;
         addButton = new JButton("Add");
    pane.add(addButton, c);
         addButton.addActionListener(this);

    Thank you for the reply
    I am new to Java
    What is wrong with the way it is coded?The error message tells you what's wrong: You're trying to reference a non-static variable from a static context.
    If you don't know what that means, then click the link I provided and look at the results from that google search. You might have to go through a few before you find a satisfactory explanation. And after you've done that, if you have specific questions about things you didn't understand there, please post again.

  • Using a static variable declared in an applet in another class

    Hi guys,
    I created an applet and i want to use one of the static variables declared in teh applet class in another class i have. however i get an error when i try to do that...
    in my Return2 class i try to call the variable infoPanel (declared as a static JPanel in myApplet...myApplet is set up like so:
    public class myApplet extends JApplet implements ActionListener, ListSelectionListener
    here are some of the lines causing a problem in the Return2 class:
    myApplet.infoPanel.removeAll();
    myApplet.infoPanel.add(functionForm2.smgframeold);
    myApplet.infoPanel.validate();
    myApplet.infoPanel.repaint();
    here are some of the errors i get
    dummy/Return2.java [211:1] package myApplet does not exist
    myApplet.infoPanel.removeAll();
    ^
    dummy/Return2.java [212:1] package myApplet does not exist
    myApplet.infoPanel.add(functionForm2.smgframeold);
    ^
    dummy/Return2.java [213:1] package myApplet does not exist
    myApplet.infoPanel.validate();
    ^
    dummy/Return2.java [214:1] package myApplet does not exist
    myApplet.infoPanel.repaint();
    ^
    please help! thanks :)

    I don't declare any packages though....i think it just doesn't recognize myApplet for some reason..
    other errors i got compiling are:
    dummy/Return2.java [82:1] cannot resolve symbol
    symbol : variable myApplet
    location: class Return2
    updateDesc.setString(3, myApplet.staticName);
    I Don't get why i'm getting this error cuase they worked fine when myApplet was a standalone application, not an applet.
    myApplet is in the same folder as Return2 and it compiles properly.

  • Loading the final static variables at run time.. Please help

    Hello, fellow developers & Gurus,
    Please help me figure out the best way to do this:
    I need to load all my constants at run time. These are the public static final instance variables. The variables values are in the DataBase. How do I go about loading them.

    Your original question was diffeent, but your further posts show what you really want to do:
    1) all constants in 1 class
    2) available readonly for other classes
    3) updatable during runtime by changing in the database
    Did I understand you right?
    Then smiths' approach solves point 2):
    Instead, make the variables available through a method
    call - that way you avoid the whole final variable
    versus read-only attributes problem.
    //GLOBAL VARIABLES EXPOSED AS PUBLIC PROPERTIES
    public final class GlobalProperties
    public static int getTableSize();
    public static int getRowSize();
    Each "constant" should be a private static variable, and these methods simply return their values.
    The variables are initialized in a static initializer by accessing the db. Ok.
    You habe a table with one row containing as columns all the constants.
    A method readConstants() does a "select constant1, constant2, ... from const_table" and sets all the variables.
    The static initializer calls this method.
    Right?
    Ok, then you simply call readConstants() everytime you want to synchronize with the actual content of const_table.
    Was it this?

  • Using Static Variable against Context Attribute for Holding IWDView

    Dear Friends,
    I have a method which is in another DC which has a parameter of the type IWDView. In my view, I will have an action which will call the method in another component by passing the value for the view parameter. Here, I can achieve this in 2 types. One is - I declare a static variable and assign the wdDoModifyView's view as parameter value and I can pass this variable as parameter whenever calling that method or the second way - create an attribute and assign the same wdDoModifyView's view parameter as its value. Whenever I call this method, I can pass this attribute as parameter. What is the difference between these two types of holding the value since I am storing the same value i.e., wdDoModifyView's view parameter. But when I trigger the action from different user sessions, the first type of code (using static variable) prints the same value in both the sessions for view.hashCode() and View.toString(), but the same is printing the different values when I pass the attribute which holds the view parameter.
    Clarification on this is highly appreciated
    The problem I face is when I use static variable to get the view instance and export the data using the UI element's id, the data belonging to different user sessions is mixed up where as when I use Context Attribute, the same problem doesn't arise. I want to know the reason why it is so. Is there any other place or way where I can get the current view instance of each session instead of wdDoModifyView?

    Hi Sujai ,
    As you have specified the problem that we face when we use  static attributes, when end users are using the application .
    Static means i  have n number of objects but the static variable value will remain same every where.
    when it is context attribute for every object i.e nth object you have a nth context attribute i mean nth copy of the context attribute.
    so every user has a unique Iview parameter , when context is used and
    when static is used  , assume you have userA , his iview is set this intially  and u have another user B , when he is using  , since the variable is static and when you access this variable you will get the value of userA.
    Regards
    Govardan Raj

  • Non-static variable Help needed

    Hi, I am creating a multi threaded web server but get the following error
    non-static variable this cannot be referenced from a static context
    HttpRequest request = new HttpRequest(connectionSocket);
    Please could someone help.
    Many Thanks
    import java.io.* ;
    import java.net.* ;
    import java.util.* ;
    public final class MultiWebServer
    public static void main(String argv[]) throws Exception
         // Set the port number.
         int port = 6789;
    // Establish the listen socket.
                   String fileName;
                   ServerSocket listenSocket = new ServerSocket(port);
    // Process HTTP service requests in an infinite loop.
    while (true) {
         // Listen for a TCP connection request.
         Socket connectionSocket = listenSocket.accept();
    // Construct an object to process the HTTP request message.
    HttpRequest request = new HttpRequest(connectionSocket);
    // Create a new thread to process the request.
    Thread thread = new Thread(request);
    // Start the thread.
    thread.start();
    final class HttpRequest implements Runnable
         final static String CRLF = "\r\n";
         Socket socket;
    String requestMessageLine;
    String fileName;
    Date todaysDate;
         // Constructor
         public HttpRequest(Socket socket) throws Exception
              this.socket = socket;
              socket = null;
    // Implement the run() method of the Runnable interface.
    public void run()
         try {
              processRequest();
         } catch (Exception e) {
              System.out.println(e);
    private void processRequest() throws Exception
         // Get a reference to the socket's input and output streams.
         //InputStream is = new InputStream(socket.getInputStream());
         //DataOutputStream os = new DataOutputStream(socket.getOutputStream());
    BufferedReader inFromClient =
                        new BufferedReader(new InputStreamReader(
                             socket.getInputStream()));
                   DataOutputStream outToClient =
                        new DataOutputStream(
                             socket.getOutputStream());
         // Set up input stream filters.
         requestMessageLine = inFromClient.readLine();
         //BufferedReader br = null;
         // Get the request line of the HTTP request message.
    String requestLine = null;
    // Display the request line.
    System.out.println();
    System.out.println(requestLine);
    StringTokenizer tokenizedLine =
                             new StringTokenizer(requestMessageLine);
                   if (tokenizedLine.nextToken().equals("GET"))
                        fileName = tokenizedLine.nextToken();
                        if ( fileName.startsWith("/")==true )
                             fileName = fileName.substring(1);
    File file = new File(fileName);
                        int numOfBytes = (int)file.length();
                        FileInputStream inFile = new FileInputStream(fileName);
                        byte[] fileInBytes = new byte[numOfBytes];
                        inFile.read(fileInBytes);
                        /* Send the HTTP header */
                        outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
                        if (fileName.endsWith(".jpg"))
                             outToClient.writeBytes("Content-Type: image/jpeg\r\n");
                        if (fileName.endsWith(".jpeg"))
                             outToClient.writeBytes("Content-Type: image/jpeg\r\n");
                        if (fileName.endsWith(".gif"))
                             outToClient.writeBytes("Content-Type: image/gif\r\n");
                        if (fileName.endsWith(".html"))
                             outToClient.writeBytes("Content-Type: text/html\r\n");
                        if (fileName.endsWith(".htm"))
                             outToClient.writeBytes("Content-Type: text/html\r\n");
                        outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
                        outToClient.writeBytes("\r\n");
                        /* Now send the actual data */
                        outToClient.write(fileInBytes, 0, numOfBytes);
                        socket.close();
                   else
                   System.out.println("Bad Request Message");
                   todaysDate = new Date();          
                   try {
                        FileInputStream inlog = new FileInputStream("log.txt");
                        System.out.println(requestMessageLine + " " + todaysDate );
                        FileOutputStream log = new FileOutputStream("log.txt", true);
                        PrintStream myOutput = new PrintStream(log);
                        myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
                   catch (IOException e) {
                   System.out.println("Error -> " + e);
                   System.exit(1);
    socket.close();

    import java.io.* ;
    import java.net.* ;
    import java.util.* ;
    public final class MultiWebServer
    public MultiWebServer(){
    try{
    // Set the port number.
    int port=6789;
    // Establish the listen socket.
    String fileName;
    ServerSocket listenSocket=new ServerSocket(port);
    // Process HTTP service requests in an infinite loop.
    while(true){
    // Listen for a TCP connection request.
    Socket connectionSocket=listenSocket.accept();
    // Construct an object to process the HTTP request message.
    HttpRequest request=new HttpRequest(connectionSocket);
    // Create a new thread to process the request.
    Thread thread=new Thread(request);
    // Start the thread.
    thread.start();
    }catch(IOException ioe){
    }catch(Exception e){
    public static void main(String argv[]) throws Exception
    new MultiWebServer();
    final class HttpRequest implements Runnable
    final static String CRLF = "\r\n";
    Socket socket;
    String requestMessageLine;
    String fileName;
    Date todaysDate;
    // Constructor
    public HttpRequest(Socket socket) throws Exception
    this.socket = socket;
    socket = null;
    // Implement the run() method of the Runnable interface.
    public void run()
    try {
    processRequest();
    } catch (Exception e) {
    System.out.println(e);
    private void processRequest() throws Exception
    // Get a reference to the socket's input and output streams.
    //InputStream is = new InputStream(socket.getInputStream());
    //DataOutputStream os = new DataOutputStream(socket.getOutputStream());
    BufferedReader inFromClient =
    new BufferedReader(new InputStreamReader(
    socket.getInputStream()));
    DataOutputStream outToClient =
    new DataOutputStream(
    socket.getOutputStream());
    // Set up input stream filters.
    requestMessageLine = inFromClient.readLine();
    //BufferedReader br = null;
    // Get the request line of the HTTP request message.
    String requestLine = null;
    // Display the request line.
    System.out.println();
    System.out.println(requestLine);
    StringTokenizer tokenizedLine =
    new StringTokenizer(requestMessageLine);
    if (tokenizedLine.nextToken().equals("GET"))
    fileName = tokenizedLine.nextToken();
    if ( fileName.startsWith("/")==true )
    fileName = fileName.substring(1);
    File file = new File(fileName);
    int numOfBytes = (int)file.length();
    FileInputStream inFile = new FileInputStream(fileName);
    byte[] fileInBytes = new byte[numOfBytes];
    inFile.read(fileInBytes);
    /* Send the HTTP header */
    outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
    if (fileName.endsWith(".jpg"))
    outToClient.writeBytes("Content-Type: image/jpeg\r\n");
    if (fileName.endsWith(".jpeg"))
    outToClient.writeBytes("Content-Type: image/jpeg\r\n");
    if (fileName.endsWith(".gif"))
    outToClient.writeBytes("Content-Type: image/gif\r\n");
    if (fileName.endsWith(".html"))
    outToClient.writeBytes("Content-Type: text/html\r\n");
    if (fileName.endsWith(".htm"))
    outToClient.writeBytes("Content-Type: text/html\r\n");
    outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
    outToClient.writeBytes("\r\n");
    /* Now send the actual data */
    outToClient.write(fileInBytes, 0, numOfBytes);
    socket.close();
    else
    System.out.println("Bad Request Message");
    todaysDate = new Date();
    try {
    FileInputStream inlog = new FileInputStream("log.txt");
    System.out.println(requestMessageLine + " " + todaysDate );
    FileOutputStream log = new FileOutputStream("log.txt", true);
    PrintStream myOutput = new PrintStream(log);
    myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
    catch (IOException e) {
    System.out.println("Error -> " + e);
    System.exit(1);
    socket.close();

Maybe you are looking for

  • Problems - WLS 10.0 web service client

    I'm having a few issues with WLS 10.0 web service client.           I generated a service control from the WSDL. The service is provided by a 3rd party (non-WLS) at another company. I generated the control within my web project and it's deployed as p

  • How to align text in a JTextArea

    Hi, I want to set the caret position to left/center/right based on an application-specified type for the JTextArea. Is there any easy way to do this?

  • Dynamically passing data into a running while loop from a DAQ assist. in an ouside while loop

    Hello,  I'm currently a student working on a senior project and I'm trying to do a state machine that will turn off and turn on a compressor depending on time and coprocessor failure.  In the run state, wich is #1 on the case structure box I placed t

  • Advanced keyboard layouts

    Hello, I want to create my own keyboard layout. I know how to do this with xmodmap and doing it through XKB doesn't seem hard either, but I'm looking for something a tad more advanced. I want to create extra modes (like caps-lock) and submaps, which

  • No Values in 0FISCYEAR

    My sid table for 0FISCYEAR is empty. Someone has played with it, So the question is how to fill it now? Edited by: Mattreed on Nov 24, 2011 8:31 PM