NullPointerException Using PrintStream or PrintWriter

Here is the code that I am using. I am taking the output of a program and trying to write that output to a file. When outputting to the file I receive a null pointer exception that I don't know why I am getting. I am using PrintStream here but I also tried using PrintWriter and I got the same error. If I uncomment the System.out.println statement the first line is printed to the console window, but then when it tries to print that line to the file I apparently get the NullPointerException. Can anyone help? Thank you. Here is that bit of code.
p = r.exec(myprogram);
                              InputStream in = p.getInputStream();
                              BufferedReader br = new BufferedReader(new InputStreamReader(in));
                              String line = null;
                              try
                                   PrintStream outFile = new PrintStream(new FileOutputStream("testresults.txt"));
                              catch(FileNotFoundException fe)
                                   System.out.println("File not found: " + fe);
                              while ((line = br.readLine()) != null)
                                   //System.out.println(line);
                                   outFile.println(line);
                              p.waitFor();

I can tell you exactly why... Here's an example
public static void aMethod() {
  String s = "Foo";
    String s = "Bar";
  System.out.println(s);
}The value output is "Foo" because the 's' declared in the parenthesis is a different variable in it's own scope.
Your code does something similar when you did the following
try {
  PrintStream outFile = new PrintStream(new FileOutputStream("testresults.txt"));
} catch(FileNotFoundException fe) {
  System.out.println("File not found: " + fe);
}This declares a variable in the scope of the try block and assigns a reference to a new PrintStream object. However this variable ceases to exist immediately following the closing parenthesis of the catch block.
Since your code compiles you must, further up have already declared outFile so I would change the code to
try {
  outFile = new PrintStream(new FileOutputStream("testresults.txt"));
} catch(FileNotFoundException fe) {
  System.out.println("File not found: " + fe);
  outfile = null;
}Note that this means if the exception occurs, outFile will be null. You need to decide what action to take in this situation.
Hope that helps - now put up your Dukes... ;)

Similar Messages

  • Writing to file using PrintStream and PrintWriter...

    I tried to write a string to a file, it actually ADD the string to the bottom of the text file without deleting what was already in there. at first I use PrintStream, it worked fine when run it from my MS-J++6.0, but it says "PrintStream has been deprecated by the author of java.io.printstream", and when I try to run it from IE it doesn't even work. then I look into the MSDN, it says jdk 1.1 prefer to use PrintWritier, so I change it to PrintWriter, no more error message but now the file only records the last string I entered and deleted all the text I had in there before. and it still doesn't work when I try to run it from IE. And for some reason, the program will creat the text file on my desktop(winXP) instead in the same folder where the java files are....
    Please help me understand what's wrong and how to solve it.. thank you. here is my code...
    public void storing(String msg)
              PrintWriter ps = null;
              try
                   ps = new PrintWriter(new FileOutputStream("collect.txt"), true);
                   ps.println(msg);
              catch (IOException e)
                   feedback.append("Cannot write to file.");
              finally
                   if(ps != null)
                        ps.close();

    cuz what I am doing is to have the user input 30 lines of messages, each time a message is written, they press a "next" button then that line of message will be saved to file, then the user can write the next line. I do this becuz I am affraid that the user will close the applet before he finishes all 30 line, if he does that, I still want to get as much line that the user has wrote that's why I have it write to file each time a line is written. So if I open a file at the beginning of the program, will it encounter any problem if the user close the applet without close the file??
    thanx.

  • PrintStream and PrintWriter

    Hi,
    Could anybody tell me the difference between PrintStream and PrintWriter ?
    I know that the first one operates on 8 bits streams whereas the second one
    on 16 bits streams. Why could the first one not handle Unicodes properly ?
    Could anybody give some explanation on that ?
    The main purpose for PrintStream is to provide ability to "print representations
    of various data values conveniently". So it handles all the data representations
    as well as char type which is 16 bit type - so it handles Unicodes - doesn't it ?
    If it does - what is the purpose for PrintWriter ?
    I got confused here ...
    Any links with some technical info about Stream and Writer compared
    will be appreciated :)
    Thanks,
    Adrian

    At its most basic, streams write out data and writers write out text. I searched the forum with just these terms -- printstream printwriter -- and got many useful hits. This included this gem:
    http://forum.java.sun.com/thread.jspa?forumID=54&threadID=641616

  • Formatting output to a text file (using FileWriter and PrintWriter)

    Hi Folks
    I am using the bit of code below to save output from a gui to a text file. The data is entered line by line in the form eg,
    "one two three four"
    "five six seven eight"
    I am also reloading this data back in to a TextArea in the GUI for viewing if required. The annoying thing that upon reloading, the data appears in one long line. The TextArea does not offer a line wrapping facilty (well I don't know how to impement it, it exist). Consequently, I would be quite grateful if somone could come come to my assistance. Any of these would graciously appreciated:
    1. Forcing the TextArea to word wrap
    2. Manually inserting some type of newline character at the end of the outbound
    text
    3. Or any other procedure you experts can dream up :-)
    Cheers
    public void actionPerformed(ActionEvent e) {
    if (e.getSource() == loadButton) {
    getFileDialog = new FileDialog(this,
    "Select or enter the name of the file you wish to write to.",
    FileDialog.LOAD);
    getFileDialog.setDirectory("C:\\Work\\java_tutorials");
    getFileDialog.show();
    fileName = getFileDialog.getFile();
    if(fileName == null) {
    return;
    directory = getNameBox.getDirectory();
    path = directory + fileName;
    fileConfirmation.setText(path);
    if (e.getSource() == saveButton ) {
    try{
    outputFile = new PrintWriter( new FileWriter(fileName, true), true);
    outputFile.print(inputTextArea.getText() );
    outputFile.close();
    catch (FileNotFoundException e1) {
    return;
    catch (NullPointerException e2) {
    return;
    catch (IOException e3) {     
    JOptionPane.showMessageDialog(null,
    "There was an error in opening this file!");
    System.exit(0);
    }

    'you can use "append()" method...
    ex.
    // some code here...
         inputTxtArea.append(data+"\n");  //<<-- you need to put '\n'
    // some code here...

  • "java.lang.NullPointerException" using the calender-iview

    Hi,
    We are using SAP NetWeaver Portal 6.0.14.0.0, KM-Version 6.0.14.2.0 and Microsoft Exchange 2000.
    Our SysAdmin has integrated Exchange into the portal and I integrated two calender-iviews (one-month-overview & one-daay-overview). Until last week everything worked fine and everybody was able to see his appointments within this two iviews. But now we get the error-message "
    java.lang.NullPointerException" in this iviews. 
    We haven´t changed anything, this error-message appeared suddenly. Has anybody an idea what´s wrong?
    Thanks for help.
    Greetings,
    Sven

    Hi Sven,
    (a) You should definitely check the log files (default.X.trc) to get a more specific idea where the error comes from.
    (b) If you don't realise immediately where the problem comes from when watching the traces, consider opening an OSS message, for at least a NPE should never be thrown on the UI.
    Hope it helps
    Detlev

  • Got NullPointerException using plain/text content in the mail.

    Hi,
    Here is the code sipnet, and i am facing problems, when i use it
            InternetAddress[] addressTo = new InternetAddress[tok.countTokens()];
            int i=0;
            while(tok.hasMoreTokens())
                addressTo[i++] = new InternetAddress(tok.nextToken());
            msg.setRecipients(Message.RecipientType.TO, addressTo);
            tok = new StringTokenizer(cc,",");
            InternetAddress[] addressCC = new InternetAddress[tok.countTokens()];
            i=0;
            while(tok.hasMoreTokens())
                addressCC[i] = new InternetAddress(tok.nextToken());
            msg.setRecipients(Message.RecipientType.CC, addressCC);
            // Optional : You can also set your custom headers in the Email if you Want
            msg.addHeader("MyHeaderName", "myHeaderValue");
            // Setting the Subject and Content Type
            msg.setSubject(subject);
            msg.setContent(message, "text/html; charset=\"UTF-8\"");
         //msg.setText(message);
            Transport.send(msg);on execution of the above code, i get the following exceptions please help..
    java.lang.NullPointerException
    at com.sun.mail.handlers.text_plain.writeTo(text_plain.java:98)
    at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:839)
    at javax.activation.DataHandler.writeTo(DataHandler.java:295)
    at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:222)
    at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1065)
    at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:1914)
    at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:1895)
    at javax.mail.Transport.send(Transport.java:79)
    at com.prosoft.workflow.extensions.SMTPMailAuthenticationExtension.postMail(SMTPMailAuthenticationExtension.java:114)
    at com.prosoft.workflow.extensions.SMTPMailAuthenticationExtension.execute(SMTPMailAuthenticationExtension.java:62)
    Any sugession also welcome.
    Thanks in advance
    Thanks,
    - Moses.

    Hi Krupa,
    Still same error .
    Transmitting the message to endpoint <local> using connection File_http://sap.com/xi/XI/System failed, due to: com.sap.engine.interfaces.messaging.api.exception.MessagingException: com.sap.aii.af.sdk.xi.srt.BubbleException: Failed to call the endpoint  [null "null"]; nested exception caused by: com.sap.aii.af.sdk.xi.util.XMLScanException: expecting end tag: {http://sap.com/xi/XI/Mail/30}Mail, but found {}Content at state

  • Problem using PrintStream to write to file.

    I am trying to write some String data to a file.
    I have replaced System.out with a PrintStream of my own.
    When I open the file with notepad,
    there are little squared at the end of each line with text written.
    I'm guessing they have something to do with
    the default character encoding on a PrintStream Object.
    I am aware that
    "All characters printed by a PrintStream are converted into bytes using the platform's default character encoding".
    as I am aware of the "java.nio.charset.Charset "
    class. I have tryed specifying UTF-8 and US-ASII
    encoding when instantiating a PrintStream Object.
    What can I do to prevent the square being written, and just using default new lines
    there, no matter how the file is viewed?
    (my OS is Windows XP service pack 2)
    ?

    Yes, I have. And yes, one would expect.
    However, it isn't.
    This is just personal code. I am doing the following:
    import java.io.File;
    import org.w3c.dom.*;
    import javax.xml.parsers.*;
    import java.io.*;
    public class DomParsing {
    public static void main (String [] args)
    try
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    File file = new File("cd-catalog.xml");
    Node child = null;
    Document document = builder.parse(file);
    Node element = (Node)document.getDocumentElement();
    FileOutputStream fileStream = new FileOutputStream("SCREEN_OUTPUT.txt");
    PrintStream logger = new PrintStream(fileStream,false);
    System.setOut(logger);
    iterate(element);
    logger.close();
    fileStream.close();
    catch (Exception e)
    {e.printStackTrace();}
    //needs closer examination.
    public static void iterate(Node element)
    while(element instanceof Node)
    peekNode(element);
    peekAttributes(element);
    Node [] children = getChildren(element);
    if(children instanceof Node[])
    //Node child = ;
    iterate(children[0]);}
    element = getSibling(element);
    //Suspect may be either of those two instructions.
    if(element instanceof Node)
    //iterate(element);
    continue;
    private static Node [] getChildren(Node element)
    Node [] children = null;
    if(element.hasChildNodes())
    NodeList nodes= element.getChildNodes();
    children = new Node [nodes.getLength()];
    for(int i=0;i<nodes.getLength();i++)
    children[i] = nodes.item(i);
    return children;}
    private static Node getSibling(Node element)
    Node sibling = element.getNextSibling();
    return sibling;}
    private static void peekNode(Node node)
    if(node instanceof Node)
    if(node.getNodeName()!=null && (!node.getNodeName().equals("#text")))
    {System.out.println(new String(node.getNodeName()));
                   System.out.println();
    if(node.getNodeValue()!=null && (!node.getNodeValue().equals("#text")))
    {System.out.println(new String(node.getNodeValue()));
                   System.out.println();
    private static void peekAttributes(Node element)
    if(element.hasAttributes())
    NamedNodeMap map = element.getAttributes();
    for(int i=0;i<map.getLength();i++)
    Attr attribute = (Attr)map.item(i);
    peekNode((Node)attribute);}
    //*******************************************************************************************************************

  • How to create a file on a remote machine using PrintStream

    I want to create an HTML file on a remote machine connect via LAN the path is "\\vineet\akh\" akh is folder where I want to save the HTML file. Now in PrintStream i can give only a local file. Please help how to do it

    .. You can do this in two ways!!
    1) easy way
    2) hard way
    1) EASY WAY
    .. as you know for write to a remote dir you must
    a) have shared remote dir
    b) have write permit on remote dir
    if you have point a) and b) the way to follow it's simple as the other user explained to you!!
    2) HARD WAY
    the hard way is to use RMI (Remote Method Invokation)
    i mean to create a service on a remote machine that give to you a remote method that make you write without share anything..!!!
    check it out
    http://tns-www.lcs.mit.edu/manuals/java-api-1.1beta2/guide/rmi/
    i hope i'm been clear!!
    SORRy My english!! (please)
    Alessandro

  • Using java.io.PrintWriter out  in servlets

    Hi,
    I have problem using Printwriter in my servlet code.
    This is what i am doing.....
    java.io.PrintWriter out = new java.io.PrintWriter(res.getOutputStream());
    out.println("Query string"+req.getQueryString());
    There is no out put on my browser. Am i missing something ..!?

    Yup actually this worked--->PrintWriter out = res.getWriter();
    instead of creating a new one.
    Also correct me if im wrong, if you have a say 4 servlets which talk to each other & each one displays its part of the display for a single display page & if you have created a PrintWriter in one of the servlets, can it be reused in other servlets or should it be reused !!

  • NullPointerException using weight based load algorithm?

              We're using WL451, on Solaris. We have two clusters, Cluster A (running
              servlets) and Cluster B (running EJB's).
              We've enabled weight-based load balancing on cluster B. Each machine
              has a weblogic.system.weight property defined.
              When running code on cluster A, we get frequent null pointer exceptions
              in Weblogic. Has anyone seen this?
              Wed Aug 30 17:11:54 EDT 2000 <E> [ShockExServlet] Unexpected failure:
              java.lang.NullPointerExceptio
              n. Exception: java.lang.NullPointerException
              java.lang.NullPointerException
              at weblogic.service.RichReplicaList.getMaxServerWeight(Compiled
              Code)
              at
              weblogic.service.WeightBasedReplicaHandler.chooseReplica(Compiled Code)
              at weblogic.service.BasicReplicaHandler.loadBalance(Compiled
              Code)
              at weblogic.service.BasicServiceStub._wl_loadBalance(Compiled
              Code)
              at
              weblogic.service.BasicServiceStub._wl_autoLoadBalance(Compiled Code)
              at
              com.shockmarket.ejb.ir.ShockInformationReceiverBeanEOImpl_ServiceStub.exOccurred(Compiled
              Code)
              at
              com.shockmarket.data.ShockInformationReceiverProxy.exOccurred(Compiled
              Code)
              at com.shockmarket.servlet.ShockExServlet.recordEx(Compiled
              Code)
              at com.shockmarket.servlet.ShockExServlet.emitHTML(Compiled
              Code)
              at com.shockmarket.servlet.ShockBaseServlet.sendHTML(Compiled
              Code)
              at com.shockmarket.servlet.ShockBaseServlet._jspService(Compiled
              Code)
              at com.shockmarket.servlet.ShockBaseServlet.doGet(Compiled Code)
              at javax.servlet.http.HttpServlet.service(Compiled Code)
              at javax.servlet.http.HttpServlet.service(Compiled Code)
              at
              weblogic.servlet.internal.ServletStubImpl.invokeServlet(Compiled Code)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(Compiled
              Code)
              and
              Wed Aug 30 17:12:01 EDT 2000 <E>
              [UUID=prodweb2.shockmarket.com967669921432] [_RG] Failed processing
              form request. data = BH=foo&U=1. Exception:
              java.lang.NullPointerException
              java.lang.NullPointerException
              at
              weblogic.service.WeightBasedReplicaHandler.chooseReplica(Compiled Code)
              at weblogic.service.BasicReplicaHandler.loadBalance(Compiled
              Code)
              at weblogic.service.BasicServiceStub._wl_loadBalance(Compiled
              Code)
              at
              weblogic.service.BasicServiceStub._wl_autoLoadBalance(Compiled Code)
              at
              com.shockmarket.ejb.subscriber.ShockSubscriberBeanHomeImpl_ServiceStub.findByBrIDB
              rHandle(Compiled Code)
              at
              com.shockmarket.ejb.ShockEJBClientUtils.getSubscriberState(Compiled
              Code)
              at
              com.shockmarket.servlet.ShockBaseServlet.getSubscriberState(Compiled
              Code)
              at
              com.shockmarket.servlet.ShockBaseServlet.getNextSubpage(Compiled Code)
              at
              com.shockmarket.servlet.ShockBaseServlet.processRequest(Compiled Code)
              at com.shockmarket.servlet.ShockBaseServlet.doGet(Compiled Code)
              at javax.servlet.http.HttpServlet.service(Compiled Code)
              at javax.servlet.http.HttpServlet.service(Compiled Code)
              at
              weblogic.servlet.internal.ServletStubImpl.invokeServlet(Compiled Code)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(Compiled
              Code)
              at weblogic.servlet.JSPServlet.service(Compiled Code)
              at javax.servlet.http.HttpServlet.service(Compiled Code)
              at
              weblogic.servlet.internal.ServletStubImpl.invokeServlet(Compiled Code)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(Compiled
              Code)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(Compiled
              Code)
              at weblogic.socket.MuxableSocketHTTP.invokeServlet(Compiled
              Code)
              at weblogic.socket.MuxableSocketHTTP.execute(Compiled Code)
              at weblogic.t3.srvr.ExecuteThread.run(Compiled Code)
              David Michaels <[email protected]>
              Director of Technology
              ShockMarket Corporation (650) 330-4665
              [david.vcf]
              

    Which service pack? Could you use most recent service pack?
              Cheers - Wei
              David Michaels <[email protected]> wrote in message
              news:[email protected]...
              >
              > We're using WL451, on Solaris. We have two clusters, Cluster A (running
              > servlets) and Cluster B (running EJB's).
              >
              > We've enabled weight-based load balancing on cluster B. Each machine
              > has a weblogic.system.weight property defined.
              >
              > When running code on cluster A, we get frequent null pointer exceptions
              > in Weblogic. Has anyone seen this?
              >
              > Wed Aug 30 17:11:54 EDT 2000 <E> [ShockExServlet] Unexpected failure:
              > java.lang.NullPointerExceptio
              > n. Exception: java.lang.NullPointerException
              > java.lang.NullPointerException
              > at weblogic.service.RichReplicaList.getMaxServerWeight(Compiled
              > Code)
              > at
              > weblogic.service.WeightBasedReplicaHandler.chooseReplica(Compiled Code)
              > at weblogic.service.BasicReplicaHandler.loadBalance(Compiled
              > Code)
              > at weblogic.service.BasicServiceStub._wl_loadBalance(Compiled
              > Code)
              > at
              > weblogic.service.BasicServiceStub._wl_autoLoadBalance(Compiled Code)
              > at
              >
              com.shockmarket.ejb.ir.ShockInformationReceiverBeanEOImpl_ServiceStub.exOccu
              rred(Compiled
              >
              > Code)
              > at
              > com.shockmarket.data.ShockInformationReceiverProxy.exOccurred(Compiled
              > Code)
              > at com.shockmarket.servlet.ShockExServlet.recordEx(Compiled
              > Code)
              > at com.shockmarket.servlet.ShockExServlet.emitHTML(Compiled
              > Code)
              > at com.shockmarket.servlet.ShockBaseServlet.sendHTML(Compiled
              > Code)
              > at com.shockmarket.servlet.ShockBaseServlet._jspService(Compiled
              >
              > Code)
              > at com.shockmarket.servlet.ShockBaseServlet.doGet(Compiled Code)
              >
              > at javax.servlet.http.HttpServlet.service(Compiled Code)
              > at javax.servlet.http.HttpServlet.service(Compiled Code)
              > at
              > weblogic.servlet.internal.ServletStubImpl.invokeServlet(Compiled Code)
              > at
              > weblogic.servlet.internal.ServletContextImpl.invokeServlet(Compiled
              > Code)
              >
              > and
              >
              > Wed Aug 30 17:12:01 EDT 2000 <E>
              > [UUID=prodweb2.shockmarket.com967669921432] [_RG] Failed processing
              > form request. data = BH=foo&U=1. Exception:
              > java.lang.NullPointerException
              > java.lang.NullPointerException
              > at
              > weblogic.service.WeightBasedReplicaHandler.chooseReplica(Compiled Code)
              > at weblogic.service.BasicReplicaHandler.loadBalance(Compiled
              > Code)
              > at weblogic.service.BasicServiceStub._wl_loadBalance(Compiled
              > Code)
              > at
              > weblogic.service.BasicServiceStub._wl_autoLoadBalance(Compiled Code)
              > at
              >
              com.shockmarket.ejb.subscriber.ShockSubscriberBeanHomeImpl_ServiceStub.findB
              yBrIDB
              >
              > rHandle(Compiled Code)
              > at
              > com.shockmarket.ejb.ShockEJBClientUtils.getSubscriberState(Compiled
              > Code)
              > at
              > com.shockmarket.servlet.ShockBaseServlet.getSubscriberState(Compiled
              > Code)
              > at
              > com.shockmarket.servlet.ShockBaseServlet.getNextSubpage(Compiled Code)
              > at
              > com.shockmarket.servlet.ShockBaseServlet.processRequest(Compiled Code)
              > at com.shockmarket.servlet.ShockBaseServlet.doGet(Compiled Code)
              >
              > at javax.servlet.http.HttpServlet.service(Compiled Code)
              > at javax.servlet.http.HttpServlet.service(Compiled Code)
              > at
              > weblogic.servlet.internal.ServletStubImpl.invokeServlet(Compiled Code)
              > at
              > weblogic.servlet.internal.ServletContextImpl.invokeServlet(Compiled
              > Code)
              > at weblogic.servlet.JSPServlet.service(Compiled Code)
              > at javax.servlet.http.HttpServlet.service(Compiled Code)
              > at
              > weblogic.servlet.internal.ServletStubImpl.invokeServlet(Compiled Code)
              > at
              > weblogic.servlet.internal.ServletContextImpl.invokeServlet(Compiled
              > Code)
              > at
              > weblogic.servlet.internal.ServletContextImpl.invokeServlet(Compiled
              > Code)
              > at weblogic.socket.MuxableSocketHTTP.invokeServlet(Compiled
              > Code)
              > at weblogic.socket.MuxableSocketHTTP.execute(Compiled Code)
              > at weblogic.t3.srvr.ExecuteThread.run(Compiled Code)
              >
              >
              > --
              > David Michaels <[email protected]>
              > Director of Technology
              > ShockMarket Corporation (650) 330-4665
              >
              >
              

  • Possible to use both a PrintWriter and BufferedOutputStream?

    I have made a PrintWriter and BufferedOutputStream on the same socket that my client uses to connect to the server. I start by sending some string with the PrintWriter followed by some bytes with the BufferedOutputStream.
    I does not work, so I would like to know if its not possible to connect these to out channels to the same socket.

    On the Client side (the PrintWriter's second argument is true so it should autoflush):
    out = new PrintWriter(socket.getOutputStream(),true);
                        String s = "sally";
                        byte[]sb = s.getBytes();
                        int len1 = sb.length;
                        out.println(len1 + "");
                       outBytes = new BufferedOutputStream(socket.getOutputStream());
                       outBytes.write(sb, 0, len1);
                       outBytes.flush();on the serverside:
                  in = new BufferedReader(
                            new InputStreamReader(
                            socket.getInputStream()));
    inBytes = new BufferedInputStream(socket.getInputStream());
                       int len1 = Integer.valueOf(in.readLine()).intValue();           
                        byte[] clientPub = new byte[len1];    
                        System.out.println("test");
                       inBytes.read(clientPub, 0, len1);
                            System.out.println("test22");test22 never gets printed so it must be inBytes.read(clientPub, 0, len1); that is blocking. But the out on the client should autoflush and I have also tried out.flush() but it does not help.

  • NullPointerException using loadbundle

    I'm a newbie to JSF and am getting a NullPointerException when trying to use the loadbundle tag. I saw someone else posted a similar post here but didn't see any resolution.
    I'm using NetBeans 4.1 and have all of my property files in a package:
    com.mycompany.myproject.bundles.Login.properties
    com.mycompany.myproject.bundles.Login_en_US.properties
    com.mycompany.myproject.bundles.Login_es_ES.properties
    etc...
    In the body of the html in my login.jsp file I'm using:
    <f:loadBundle basename="com.mycompany.myproject.bundles.Login" var="loginBundle" />
    I don't know if this is relavent, but this is how the url pattern looks in my web.xml:
    <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
    </servlet-mapping>
    Anyone have any idea? TIA.

    Nevermind I figured this out...
    I had to manually add library references to jstl.jar and standard.jar. Don't know why they are automatically added? :-\
    I also changed the url mapping to *.jsf (just my preference). During debugging with NetBeans you have to manually type in the name of the altered page name (login.jsf instead of login.jsp). I also added preventive-access security settings to the web.xml:
    <security-constraint>
    <display-name>Restrict access to JSP pages</display-name>
    <web-resource-collection>
    <web-resource-name>
              Restrict access to JSP pages
    </web-resource-name>
         <url-pattern>*.jsp</url-pattern>
         </web-resource-collection>
    <auth-constraint>
    <description>
    With no roles defined, no access granted
    </description>
    </auth-constraint>
    </security-constraint>
    That way the *.jsp pages cannot be accessed directly (since they need to go through the faces servelet via *.jsf).
    Sort of a pain-in-the-ass IMO.

  • NullPointerException using DeploymentXMLGenerator

    Hi,
    I'm using JDeveloper 10.1.3.2 with TopLink. I'm building the application with Maven and I would like during the build process to export the mappings.
    I found out that the DeploymentXMLGenerator class mentionned in the TopLink docs was located in tl_mappingeditor.jar under JDEV_HOME/jdev/lib. So I'm trying to use it to generate the xml deployment descriptor, however I'm always getting a NullPointerException:
    java.lang.NullPointerException
            at oracle.toplink.workbench.external.api.Generator.generate(Generator.java:65)I'm using the following code:
    new DeploymentXMLGenerator().generate(new File("path-to-mwp-file"), new File("path-to-xml-file"));What's wrong? Is there another way around?
    Thanx
    Olivier

    I should probably give a more accurate example. The original is over-simplified and you might think I am passing null into setObject().
    for ( int j = 0; j < data.length; j++ ) {
    for ( int k = 0; k < data[j].length; k++ ) {
    if ( data[j][k] == null ) {
    statement.setNull(k + 1, getSqlType(k));
    } else {
    statement.setObject(k + 1, data[j][k]);
    statement.addBatch();
    statement.executeBatch();

  • NullPointerException using xjc

    I'd like to use xjc to generate the Java Bindings from my schemas.
    Using the console to start xjc (xjc ATE_Display.xsd ATE_Template.xsd) I've got the following error.
    Exception in thread "main" java.lang.NullPointerException
         at com.sun.tools.xjc.reader.xmlschema.BGMBuilder._getBindInfoReadOnly(BGMBuilder.java:383)
         at com.sun.tools.xjc.reader.xmlschema.BGMBuilder.getBindInfo(BGMBuilder.java:367)
         at com.sun.tools.xjc.reader.xmlschema.BGMBuilder.getLocalDomCustomization(BGMBuilder.java:405)
         at com.sun.tools.xjc.reader.xmlschema.RawTypeSetBuilder.particle(RawTypeSetBuilder.java:79)
         at com.sun.tools.xjc.reader.xmlschema.RawTypeSetBuilder.build(RawTypeSetBuilder.java:43)
         at com.sun.tools.xjc.reader.xmlschema.ct.MixedComplexTypeBuilder.build(MixedComplexTypeBuilder.java:46)
         at com.sun.tools.xjc.reader.xmlschema.ct.ComplexTypeFieldBuilder.build(ComplexTypeFieldBuilder.java:64)
         at com.sun.tools.xjc.reader.xmlschema.BindRed.complexType(BindRed.java:37)
         at com.sun.xml.xsom.impl.ComplexTypeImpl.visit(ComplexTypeImpl.java:237)
         at com.sun.tools.xjc.reader.xmlschema.ClassSelector$Binding.build(ClassSelector.java:175)
         at com.sun.tools.xjc.reader.xmlschema.ClassSelector.executeTasks(ClassSelector.java:321)
         at com.sun.tools.xjc.reader.xmlschema.BGMBuilder._build(BGMBuilder.java:139)
         at com.sun.tools.xjc.reader.xmlschema.BGMBuilder.build(BGMBuilder.java:77)
         at com.sun.tools.xjc.ModelLoader.annotateXMLSchema(ModelLoader.java:387)
         at com.sun.tools.xjc.ModelLoader.load(ModelLoader.java:145)
         at com.sun.tools.xjc.ModelLoader.load(ModelLoader.java:91)
         at com.sun.tools.xjc.Driver.run(Driver.java:287)
         at com.sun.tools.xjc.Driver.run(Driver.java:173)
         at com.sun.tools.xjc.Driver._main(Driver.java:98)
         at com.sun.tools.xjc.Driver.access$000(Driver.java:56)
         at com.sun.tools.xjc.Driver$1.run(Driver.java:78)
    I am using Java 1.5.0_08 & Jaxb2_20060801

    Yes I am using JAXB2 (JAXB2_20060801) & java 1.5.0_08
    I tried the "Simple Mode" (with the call xjc -extension simpleMode.xsd ATE_Display.xsd ATE_Template.xsd) described at the Website you posted me, but the error message was just the same as before.

  • ExecutorService using bufferwriter and printwriter

    I'm trying to create a simple multithread chat server for class. when i run the server and connet with multiple clients the server only outputs to one client. it also appears that the server will keep a running list of who sent data to the server, but will only repot back to the last connected client.
    I need help
    the java code is located at the attached link.
    [http://www.ralieghnet.com/?q=node/23]

    *** chatServer ***
    import java.net.*;
    import java.io.*;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    public class chatserver {
          private final static int maxClients = 10;
    public static void main(String[] args){
            ServerSocket sock = null;
            Socket client = null;
            ExecutorService threadExecutor = Executors.newFixedThreadPool(maxClients);
            chatServerConnections chatConnection = new chatServerConnections();
            try{
                sock = new ServerSocket(6013);
                System.out.println("Now accepting Connections");
                while(true)
                    chatConnection.chatConnections(sock.accept());
                    chatServerListener chatListen = new chatServerListener(chatConnection);
             threadExecutor.execute((Runnable) chatListen);
            catch (IOException ioe){
                System.err.println(ioe);
    }*** chatServerConnection ***
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    public class chatServerConnections
    private Socket clientSocket;
    private BufferedReader input;
    private PrintWriter output;
            chatServerConnections()
               clientSocket = null;
               input = null;
               output = null;          
    public void chatConnections(Socket socket)
                clientSocket = socket;
                System.out.println(clientSocket);
                try{
                    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    output = new PrintWriter(socket.getOutputStream());
                catch (IOException ioe)
                    System.err.println(ioe);
    public String getInput() throws IOException
                String temp;
                temp = input.readLine();
                input.reset();
                return temp;
    public void setOutput(String inString)
                output.println(inString);
                output.flush();
            public String getAddress()
                return " connected @ " + clientSocket.getLocalAddress() +" " +clientSocket.getLocalPort() +" >>";
    }*** chatServerListener ***
    import java.net.Socket;
    import java.io.*;
    class chatServerListener implements Runnable{
        private String userName = null, userInput = "";
        private chatServerFile csf;
        private chatServerConnections chatConnect;
        public chatServerListener(chatServerConnections connect) throws IOException
            chatConnect =  connect;
            csf = new chatServerFile();
        chatServerListener() {
            throw new UnsupportedOperationException("Not yet implemented");
        public void run()
            try
                if(userName == null)
                    userName = chatConnect.getInput();
                    //userName = input.readLine();
                    chatConnect.setOutput("<< User: " + userName + " connected.>>");
                    //output.println("<< User: " + userName + " connected.>>");
                    System.out.println("<< User " + userName + chatConnect.getAddress());
                    csf.addData("<< User " + userName + chatConnect.getAddress());
            catch (IOException ioe)
                System.err.println(ioe);
            try{
                while(!(userInput == null))
                    userInput = chatConnect.getInput();
                    try
                    if(!(userInput.equalsIgnoreCase("")))
                         if(userInput.equalsIgnoreCase("GetHistory"))
                          try{
                           userInput = csf.getData();
                                 if(userInput == null)
                                  userInput = "<< SERVER: Could not complete the requested action >>";
                          catch (IOException ioe)
                           System.err.println(ioe);
                         else if(userInput.equalsIgnoreCase("quit"))
                          try{
                           chatConnect.setOutput("<< Good By >>");
                              csf.addData("<< User: " +userName + " Disconnected >>");
                              //clientSocket.close();
                              break;
                          catch (IOException ioe)
                           System.err.println(ioe);
                         csf.addData("\n" +userName + ": " + userInput);
                            chatConnect.setOutput(userName +": " +userInput);
                            if(userInput != null)
                             System.out.println(userName +": " +userInput);               
                    catch (NullPointerException npe)
                     System.err.println(npe);
                     csf.closeFile();
                System.out.println("<< User: " +userName + " Disconnected >>");
                csf.closeFile();
            catch (IOException ioe)
                System.err.println(ioe);
                System.out.println("<< User: " +userName + " Disconnected >>");
                csf.closeFile();

Maybe you are looking for