Java IO readLine

Hi, I've got a problemm
I'm currently trying to implement a small client/server application (well the client side of it)
the server sends few commands, but at the moment each command+data doesn't end with a new line symbol (at the moment end of each 'packet' symbolised my '$' character)
I'd love to modify the server, but i do not have the acess to the sources.
Is there any way i can write an inplementation that will break data recived into pieces in the same way that data would ahve been brocken down based on new line symbol, but instead use '$'?
Any help will be greatly appreciated, (i know this should be pretty simple but i'm new to this)
Cheers, Nick

Hi,
readLine stop reading line when encounter an end of line symbol.
So you can put instead of your "$" the character "\n" (eventually "\0").
In this manner you read from the stream with readLine.
If your problem is to change "$" character into some other character in the stream, let read the tutorial about the Stream (http://java.sun.com/docs/books/tutorial/essential/io/datasinks.html)
Bye, Anteo.

Similar Messages

  • Trying to understand the new Console.readline()

    I tried the following:
    public class Forum
       public static void main(String[] args)
          System.out.println("Enter a line of text:") ;
          String input = System.console().readline() ;
          System.out.println("You entered " + input) ;
    }but I get the following error:
    C:\...\Forum.java:6: readline(boolean) in java.io.Console cannot be applied to ()I don?t see a readline(boolean) method in the Console class.
    What am I missing?
    Also, what does it mean ? ??cannot be applied to ()?
    Thanx to one and all.

    JoachimSauer wrote:
    That's a confusing error message and I couldn't believe that you got that one, until I tried it.
    It seems there's a (probably private) readline(boolean) method in Console, which results in that message.
    The method you like to call is called "readLine" (not the capital L).Picky, picky, picky.
    Thanx a lot.

  • Should I go utf8 all the way?

    I think I need some advise on the topic of encodings. My system right now is a mess: One old Windows partition (NTFS), one shared FAT32 partition, both with files from a long time ago in i don't know which encoding, filenames with and without non-ascii characters, etc.
    Then there are the linux partitions with mostly new files created under my current locale, en_GB, although i tried out en_GB.utf8 for a while.
    My files are partly English, partly Norwegian/Swedish, so I need to accomodate the special characters of those languages, but I have no need neither for Arabic nor Korean/Japanese etc.
    When I would still like to switch to a fully unicoded system, it's partly to  avoid the mess, but mostly because some  of the programs I need and use on a daily basis, require unicode files (lilypond, etc.). I've had some programs complain about incorrect file name encoding (gwenview, I think, or perhaps gqview), and my file names with non-ascii characters show up in several different ways, and, it seems, differently in X-apps, in consoles, in terminals, in vim, etc.
    So, there you have my situation. Does anyone have experience - good or bad - with this kind of situation? Ideally, I suppose, I'd like all my files to be properly unicoded, both regarding file names and contents. But I assume this involves a potentially "dangerous" situation with a batch job with iconv?
    What are the pitfalls I need to keep in mind before I do this? Are there other solutions I might consider? What about apps which don't support unicode - would I be better off staying in latin1 - perhaps converting everything to that instead of unicode? As I said, in terms of characters, I really don't need more than what latin1 can offer, but some apps require unicode for the file encoding.
    Any help, feedback, pointers to good sites, etc. are appreciated.

    apps not supporting unicode tend to be rare these days, as most apps are built on qt, gtk, python, java, mono, readline, etc... and thus support utf8 OOTB.
    IIRC (some part of) zsh does not support unicode.
    you should also make clear distinction on multiple things:
    1. display/input uft8
    2. utf8 filenames in filesystem(s)
    3. utf8 file contents
    gentoo has good reference:
    http://gentoo-wiki.com/HOWTO_Create_an_ … led_system
    http://gentoo-wiki.com/HOWTO_Make_your_ … code/utf-8
    as for my advice, I'd say go for utf8 all the way. when you're on the rails, it's just transparent, and if you happen to have some file/contents having some 'weird' character in it, you'll always be okay ('weird' being relative, you don't need to go as far as Arabic: that could simply be a simple accented character not present in your ISO-* set). why be restricted when you can just as well be open? you never know what might be your need tomorrow: e.g I'm french (accented chars), I got on to learn japanese (obvious chars), and I may be in relation occasionally with at least spanish (tilda chars), and german (umlauts and ss) someday in my work. I woudn't want to have to handle 5 charsets, or to convert to utf8 at that time, so I took things in hand right now, ready and set.
    personnally the first thing I do when I install arch is locale-gen en_US.UTF-8 and set locale to it.
    as for windows compatibility, NTFS filenames are stored as utf8 IIRC, and fat32 can have utf8 enabled, though IIRC it makes the fs case sensitive. regarding file contents, most not too old windows software usually handle utf8 correctly (at least never had a problem, when I still had windows). issues arise when files are stored in non-iso windows encoding (cp1252 and the like), which I was never able to convert successfully, yet it can just be my fault for not trying hard enough (because the few files I had being non-utf8 were not that important).
    EDIT: some additions
    Last edited by lloeki (2007-04-23 12:30:28)

  • Upload csv file data to sql server tables

    Hi all,
    I want clients to upload csv file from their machines to the server.
    Then the program should read all the data from the csv file and do a bulk insert into the SQL Server tables.
    Please help me of how to go about doing this.
    Thanx in advance.....

    1) Use a multipart form with input type="file" to let the client choose a file.
    2) Get the binary stream and put it in a BufferedReader.
    3) Read each line and map it to a DTO and add each DTO to a list.
    4) Persist the list of DTO's.
    Helpful links:
    1) http://www.google.com/search?q=jsp+upload+file
    2) http://www.google.com/search?q=java+io+tutorial
    3) http://www.google.com/search?q=java+bufferedreader+readline
    4) http://www.google.com/search?q=jdbc+tutorial and http://www.google.com/search?q=sql+tutorial

  • What's wrong with Java readline()?

    I just updated to OS X 10.6.8 and installed the Java update 1.6.0_26-b03-384.
    It appears that BufferedReader.readLine() is broken for reading input lines from the console.  readLine() does not terminate with a newline.
    This is pretty basic.  What's up?
    import java.io.*;
              This class demonstrates how to read a line of text from the keyboard
    class ReadLine{
              public static void main(String[] args) throws IOException{
                        String CurLine = ""; // Line read from standard in
                        System.out.println("Enter a line of text (type 'quit' to exit): ");
                        InputStreamReader converter = new InputStreamReader(System.in);
                        BufferedReader in = new BufferedReader(converter);
                        while (!(CurLine.equals("quit"))){
                                  CurLine = in.readLine();
                                  if (!(CurLine.equals("quit"))){
                                            System.out.println("You typed: " + CurLine);

    As it turns out, there's nothing wrong with ReadLine(), the problem was Ant 1.8.2.
    http://issues.apache.org/bugzilla/show_bug.cgi?id=50960
    The Apache distribution is dated late 2010.  The Apple version of 1.8.2 states that it was compiled on June 3, 2011, but if Apple built from the distribution and not from the corrected svn trunk that would explain it.
    My work-around was to install and link ant 1.8.1.

  • ReadLine() in java.io.DataInputStream has been deprecated

    Hi,
    I am using the following code :
    File f=new File(filePath);
                   FileInputStream fis=new FileInputStream(f);
                   BufferedInputStream bis = new BufferedInputStream(fis);
    dis = new DataInputStream(bis);
                   while((record=dis.readLine())!=null){
    upon compiling this i am getting the following warning:
    warning: readLine() in java.io.DataInputStream has been deprecated
                   while((record=dis.readLine())!=null){
    ^
    1 warning
    Can anyone tell me what should I use instead of readline()?

    Read the API. It says you should make use of BufferedReader instead of DataInputStream to use readLine()

  • Applet java file not refreshing in browser

    I have an applet that I am updating and I am not seeing the corresponding update when I open the web page. I can manually download the java class file and look inside it and it definitely is the updated file. I have deleted the browser history. (I am running tests with Firefox 3, IE7, and Safari 4 public beta). Is there something else I need to do to make sure the browser pulls in the latest version of the class file referenced in the html?
    Here is the code:
    <HTML>
    <HEAD>
       <TITLE>A Simple Program</TITLE>
    </HEAD>
    <BODY>
       <CENTER>
          <APPLET CODE="SendRequest.class" WIDTH="500" HEIGHT="150">
          </APPLET>
       </CENTER>
    </BODY>
    </HTML>The applet refers to a hard coded URL to read through a urlconnection. It is always reading a file and showing content, but it is not showing the right file. If I change the name of the referenced file in the java program, it looks like the browser has cached the referred file, rather than throwing and error and saying the file doesn't exist.
    Here is the java
    import java.applet.*;
    import java.awt.*;
    import java.net.URLConnection;
    import java.net.URL;
    import org.w3c.dom.Document;
    import java.lang.String;
    import java.io.*;
    public class SendRequest extends Applet {
        @Override
        public void paint(Graphics g) {
            g.drawRect(0, 0, 499, 149);
            g.drawString(getResponseText(), 5, 70);
        public String getResponseText() {
            try {
                URL url = new URL("http://myserver.com/stats/logs/ex20090603000001-72.167.131.217.log");
                URLConnection urlconn = url.openConnection();
                BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                    urlconn.getInputStream()));
                String inputLine;
                String htmlFile = "";
                try {
                    while ((inputLine = in.readLine()) != null)
                        htmlFile += inputLine;
                    in.close();
                    return htmlFile;
                } catch (Exception e) {
                    return "Can't get the string.";
            } catch (Exception e) {
                return "Problem accessing the response text.";
    }Any help would be appreciated. I heard that some files may cache more persistently than others, but I don't fully understand the details.
    Thanks,
    Jim

    Check this [document loader example|http://pscode.org/test/docload/] & follow the link to sandbox.html for tips on clearing the class cache. That relates specifically to caching a refused security certificate, but class caching is much the same. As an aside, getting a console can be tricky in modern times (unless the applet fails completely). It is handy to configure the [Java Control Panel|http://java.sun.com/docs/books/tutorial/information/player.jnlp] to pop the Java console on finding an applet (Advanced tab - Settings/Java Console/Show Console).
    Of course there are two better tools for testing applets, especially in regard to class caching. AppletViewer and Appleteer both make class refresh fairly easy. Appleteer is the better of the two. I can tell you that with confidence, since I wrote it. ;-)

  • Urgent!! running system command in java

    i am trying to run system command(windows) in java. I am getting
    exception as java.io.IOException: CreateProcess: c:\dir
    Please Help.
    Here is the code
    import java.io.*;
    public class RunCommand {
    public static void main(String[] args) {
    try
    //run dir command
    Process p = Runtime.getRuntime().exec("c:\\dir");
    BufferedReader stdInput=new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    BufferedReader stdError =new BufferedReader(new
    InputStreamReader(p.getErrorStream()));
    //read the output
    System.out.println("here is the output:\n");
    while((s=stdInput.readLine())!=null){
    System.out.println(s);
    System.out.println("here is the error if any");
    while((s=stdError.readLine())!=null){
    System.out.println(s);
    System.exit(0);
    }//end try
    catch (IOException e)
    System.out.println("exception Happened" );
    e.printStackTrace();
    System.exit(-1);

    It works fine if you replaceProcess p = Runtime.getRuntime().exec("c:\\dir");withProcess p = Runtime.getRuntime().exec("cmd /c dir");And don't forget to define your s variable.

  • Executing shell commands in Java

    Hi
    I have managed to get my Java program to execute the 'who' command and read in the data from running that command. However, how can I run this command with the '-m' option. I thought it would be
    Process proc = rt.exec("who -m");However when I run this, I get no data. Is there another way of running this command.
    Many thanks
    Sambo

    Thanks for the link, its actually the tutorial I looked at to start using the exec method.
    try{
                   Runtime rt = Runtime.getRuntime();
                   Process proc = rt.exec("who");
                   InputStream stderr = proc.getInputStream();
                   InputStreamReader isr = new InputStreamReader(stderr);
                   BufferedReader br = new BufferedReader(isr);
                   File file = new File("input.txt");
                   BufferedWriter out = new BufferedWriter(new FileWriter(file));
                   while ((line = br.readLine())!=null){
                        temp = line.split("\\s+");
                        for (int i = 0; i < temp.length; i++){
                            //System.out.println(temp);
    This is my current code, and I can get an output from that. But as soon as I add a argument to the who command, it doesn't display anything. The who command displays the current users logged into a Linux system.
    I have tried
    Process proc = rt.exec("who -m");and
    Process proc = rt.exec("who ", "-m");But no luck.
    Maybe I have to specify it as another argument, but not to sure how to do that.
    Again many thanks

  • I want to execute [b]some shell [/b]commands in a java program

    Hello,
    I would like to know if it's possible to execute some unix commands in the same "environment"... I mean, if I use the exec() function to execute the "cd /tmp" command, and after that, if I want to do "ls" , I'm not in the "/tmp" directory, know what I mean ??
    In fact, I want to have in my GUI a textarea or something like that, in which one can enter several unix command like in a xterm window...
    I don't know how to do that and if it's possible ??
    Thank you very much for your answers !

    OK !! It works with this code but I don't understand why I have to do "return" twice before the command execute ??
    (I'm a newbie)
    Here's the sample code:
    import java.io.*;
    public class Tonta {
    private String dada="";
    private BufferedReader in;
    private InputStream instr;
    private InputStream errstr;
    private PrintStream outstr;
    private Process transyt;
    private Tonta t;
    public Tonta() {
    //Executem el programa
    try {
    transyt=Runtime.getRuntime().exec("ksh");
    System.out.print("toto");
    } catch (IOException e)
    {System.out.println("EXCEPCION:exec"+ e.getMessage());}
    instr= transyt.getInputStream();
    errstr= transyt.getErrorStream();
    outstr= new PrintStream(transyt.getOutputStream());
    in = new BufferedReader( new InputStreamReader(System.in));
    }//end of constructor
      public void run() {
        int exit=0;
        boolean processEnded= false;
        try {
          while (!processEnded) {
            try {
              exit = transyt.exitValue();
              processEnded = true;
            catch (IllegalThreadStateException e) {}
            System.out.print("\nREMOT:");
            System.out.flush();
            int n= instr.available();
            if (n>0) {
              byte[] pbytes= new byte[n];
              instr.read(pbytes);
              System.out.print(new String(pbytes));
              System.out.flush();
            n= errstr.available();
            if (n>0) {
              byte[] pbytes= new
              byte[n];
              errstr.read(pbytes);
              System.err.print(new
              String(pbytes));
              System.err.flush();
            System.out.println();
            System.out.print("LOCAL> ");
            System.out.flush();
            dada= in.readLine();
            if (dada.equals("exit")) {
              System.out.println();
              System.out.println("Programa finalizado");
              System.out.flush();
              transyt.destroy();
              instr.close();
              errstr.close();
              outstr.close();
              System.exit(0);
            outstr.println(dada);
            outstr.flush();
            try {
              Thread.sleep(10);
            catch (InterruptedException e) {}
          System.out.println();
          System.out.println("Process exited with:"+ exit);
          System.out.flush();
        } catch (IOException e) {
            System.err.println("EXCEPCION "+ e.getMessage());
    public static void main (String [] args) {
    Tonta t= new Tonta();
    t.run();
    }Thanks

  • Java Program with Adapter / Facade Pattern

    Hey All:
    I'm very new to the Java language and have been given a fairly complicated (to me) program to do for a course I'm taking. The following is the scenario. I'll post code examples I have and any help will be greatly appreciated. Let me apologize ahead of time for all the code involved and say thank you in advance :).
    The program is the follow the following logic:
    Organizations A's Client (Org_A_Client.java) uses Organization A's interface (Org_A_Interface.java) but we want A's Client to also be able to use Organization B's services as well (Org_B_FileAuthorMgr.java, Org_B_FileDateMgr.java, Org_B_FileIOMgr.java).
    Now a portion of this program also involves validating an xml file to it's dtd, extracting information from that source xml file through the use of a XMLTransformation file, and applying the transformation to produce a targetxml file which is then validated against a target DTD. (I've done this portion as I have a much better understanding of XML).
    At this point we have been given the following java classes:
    Org_A_Client.java
    package project4;
    /* This class is the Organization A Client.
    It reads a source xml file as input and it invokes methods defined in the
    Org_A_Doc_Interface Interface on a class that implements that interface */
    import java.io.*;
    import java.util.Scanner;
    public class Org_A_Client {
         // Define a document object of type Org_A_Doc_Interface
         private Org_A_Doc_Interface document;
         // The Org_A_Client constructor
         public Org_A_Client() {
              // Instanciate the document object with a class that implements the
              // Org_A_Doc_Interface
              this.document = new Adapter();
         // The Main Method
         public static void main(String Args[]) {
              // Instanciate a Client Object
              Org_A_Client client = new Org_A_Client();
              // Create a string to store user input
              String inputFile = null;
              System.out.print("Input file name: ");
              // Read the Source xml file name provided as a command line argument
              Scanner scanner = new Scanner(System.in);
              inputFile = scanner.next();
              // Create a string to store user input
              String fileID = null;
              System.out.print("Input file ID: ");
              // Read the Source xml file name provided as a command line argument
              fileID = scanner.next();
              //Convert the String fileID to an integer value
              int intFileID = Integer.parseInt(fileID);
              if (inputFile != null && !inputFile.equals("")) {
                   // Create and empty string to store the source xml file
                   String file = "";
                   try {
                        // Open the file
                        FileInputStream fstream = new FileInputStream(inputFile);
                        // Convert our input stream to a
                        // BufferedReader
                        BufferedReader d = new BufferedReader(new InputStreamReader(
                                  fstream));
                        // Continue to read lines while
                        // there are still some left to read
                        String temp = "";
                        while ((temp = d.readLine()) != null) {
                             // Add file contents to a String
                             file = file + temp;
                        d.close();
                        // The Client Calls the archiveDoc Method on the Org_A_Document
                        // object
                        if (!file.equals("")) {
                             client.document.archiveDoc(file, intFileID);
                   } catch (Exception e) {
                        System.err.println("File input error");
              } else
                   System.out.println("Error: Invalid Input");
    Org_A_Doc_Interface.java
    package project4;
    /* This class is the Standard Organization A Document Interface.
    * It defines various methods that any XML document object
    * in Organization A should understand
    public interface Org_A_Doc_Interface {
         void archiveDoc(String XMLSourceDoc, int fileID);
         String getDoc(int fileID);
         String getDocDate(int fileID);
         void setDocDate(String date, int fileID);
         String[] getDocAuthors(int fileID);
         void setDocAuthor(String authorname, int position, int fileID);
    Org_B_FileAuthorMgr.java
    package project4;
    public class Org_B_FileAuthorMgr {
         // This function returns the list of file authors for the file that matches
         // the given fileID. For the purpose of the assignment we have not
         // provided any implementation
         public String[] getFileAuthors(String fileID) {
              // Since we do not have any implementation, we just return a
              // null String array of size 2
              return new String[2];
         // This function sets the authorname at a given position for the file that
         // matches the given fileID.
         // For the purpose of the assignment we have not provided any
         // implementation
         public void setFileAuthor(String authorname, int position, String fileID) {
    Org_B_FileDateMgr.java
    package project4;
    public class Org_B_FileDateMgr {
         // This function returns the creation date for the file that matches
         // the given fileID. For the puprposes of the assignment we have not
         // provided any implementation but only return a date string.
         String getFileDate(String fileID) {
              return "1st Nov 2007";
         // This function sets the creation datefor the file that
         // matches the given fileID.
         // For the puprposes of the assignment we have not provided any
         // implementation
         void setFileDate(String date, String fileID) {
    Org_B_FileIOMgr.java
    package project4;
    import java.io.*;
    public class Org_B_FileIOMgr {
         // This class variable stores the file location for all files
         private String fileLocation;
         // This function stores the given String of XMLTargetFile at the
         // fileLocation which is set using the setFileLocation method
         boolean storeFile(String XMLTargetFile, String fileID) {
              if (this.fileLocation != null) {
                   FileOutputStream out; // declare a file output object
                   PrintStream p; // declare a print stream object
                   try {
                        // Create a new file output stream
                        // connected to "myfile.txt"
                        out = new FileOutputStream(fileLocation);
                        // Connect print stream to the output stream
                        p = new PrintStream(out);
                        p.println(XMLTargetFile);
                        p.close();
                        System.out.println("MSG from Org_B_FileIOMgr: Target File Successfully Saved with ID " + fileID);
                   } catch (Exception e) {
                        System.err.println("Error writing to file");
                        return false;
                   return true;
              System.out.println("MSG from Org_B_FileIOMgr: Please set the File Location before storing a file");
              return false;
         // This function sets the fileLocation where the file will be stored for
         // archive
         void setFileLocation(String fileLocation) {
              this.fileLocation = fileLocation;
         // This function retreives the file that matches the given fileID and
         // returns its contents as a string
         // Only for the puprposes of the assignment we have not provided any
         // implementation
         String retrieveFile(String fileID) {
              return "This is the retreived file";
    }Also, we've been given the following two classes which I believe are used to help with the xml transformation using SAX (I've done alot of research regarding parsing XML using SAX/DOM so I understand how it works, but I'm really struggling with the integration...)
    FileDetailsProvider.java
    package project4;
    /* This is the FileDetailsProvider Class which implements the Singleton design pattern.
    The class can be used in the following manner:
         // Declare a object of the class type
            FileDetailsProvider fp;
            // Get the single instance of this class by calling the getInstance static method
            fp= FileDetailsProvider.getInstance();
            // Initialize the class with providing it the file name of our configuration XML file
              fp.loadConfigFile("C:\\assignment4\\XMLTransformerConfig.xml");
    import java.io.File;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    public class FileDetailsProvider {
         private InputHandler handler;
         private SAXParserFactory factory;
         private SAXParser saxParser;
         private final static FileDetailsProvider INSTANCE = new FileDetailsProvider();
         // Private constructor suppresses generation of a (public) default
         // constructor
         private FileDetailsProvider() {
              // Create the content handler
              handler = new InputHandler();
              // Use the default (non-validating) parser
              factory = SAXParserFactory.newInstance();
              // Validate the XML as it is parsed by the SAX Parser: only works
              // for dtd's
              factory.setValidating(true);
              try {
                   saxParser = factory.newSAXParser();
              } catch (Throwable t) {
                   t.printStackTrace();
                   System.exit(0);
         // This is the public static method that returns a single instance of the
         // class everytime it is invoked
         public static FileDetailsProvider getInstance() {
              return INSTANCE;
         // After instantiation this method needs to be called to load the XMLTransformer Configuration xml
         // file that includes the xsl file details needed
         // for our assignment
         public void loadConfigFile(String configFile) {
              try {
                   INSTANCE.saxParser.parse(new File(configFile), INSTANCE.handler);
              } catch (Throwable t) {
                   t.printStackTrace();
                   // Exceptions thrown if validation fails or file not found
                   System.out.println();
                   System.out.println("C:\\Documents and Settings\\Jig\\Desktop\\Project 4\\Project4\\Transform.xsl");
                   System.exit(0);
         // This method return the xsl file name
         public String getXslfileName() {
              return handler.getXslfileName();
         // This method returns the xsl file location
         public String getXslfileLocation() {
              return handler.getXslfileLocation();
    InputHandler.java
    package project4;
    /* This class is used by the FileDetailsProvider Class to read the XMLTranformerConfig xml
    * file using a SAX parser which is a event based parser
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.helpers.DefaultHandler;
    public class InputHandler extends DefaultHandler {
         private String xslfileName = "";
         private String xslfileLocation = "";
         int fileName = 0, fileLoc = 0, DTDUrl = 0;
         boolean endOfFile = false;
         public InputHandler() {
         // Start XML Document Event
         public void startDocument() throws SAXException {
              super.startDocument();
         // End XML Document Event
         public void endDocument() throws SAXException {
              super.endDocument();
              // display();
         public void display() {
              System.out.println(xslfileName);
              System.out.println(xslfileLocation);
         public void startElement(String uri, String localName, String qName,
                   Attributes attributes) throws SAXException {
              String eName = localName; // element name
              if ("".equals(eName))
                   eName = qName; // not namespace-aware
              if (eName.equals("File Name:")) {
                   fileName++;
              } else if (eName.equals("File Location:")) {
                   fileLoc++;
         public void endElement(String uri, String localName, String qName)
                   throws SAXException {
              String eName = localName; // element name
              if ("".equals(eName))
                   eName = qName; // not namespace-aware
         public void characters(char ch[], int start, int length)
                   throws SAXException {
              String str = new String(ch, start, length);
              // Getting the Transform File Location
              if (fileLoc == 1 && xslfileLocation.equals("C:\\Documents and Settings\\Jig\\Desktop\\Project 4\\Project4\\")) {
                   xslfileLocation = str;
              // Getting the Transform File Name
              if (fileName == 1 && xslfileName.equals("Transform.xsl")) {
                   xslfileName = str;
         public void processingInstruction(String target, String data)
                   throws SAXException {
         // treat validation errors as fatal
         public void error(SAXParseException e) throws SAXParseException {
              throw e;
         // This method return the xsl file name
         public String getXslfileName() {
              return xslfileName;
         // This method returns the xsl file location
         public String getXslfileLocation() {
              return xslfileLocation;
    }I need to do the following:
    1. Create an adapter class and a facade class that allows Client A through the use of Organization's A interface to to use Organization B's services.
    2. Validate the Source XML against its DTD
    3. Extract information regarding the XSL file from the given XMLTransformerConfig xml file
    4. Apply the XSL Transformation to the source XML file to produce the target XML
    5. Validate the Target XML against its DTD
    Now I'm not asking for a free handout with this program completed as I really want to learn how to do a program like this, but I really don't have ANY prior java experience other than creating basic classes and methods. I don't know how to bring the whole program together in order to make it all work, so any guidance for making this work would be greatly appreciated.
    I've researched over 100 links on the web and found alot of useful information on adapter patterns with java and facade patterns, as well as SAX/DOM examples for parsing xml documents and validation of the DTD, but I can't find anything that ties this all together. Your help will be saving my grade...I hope :). Thanks so much for reading this.

    No one has anything to add for working on this project? I could really use some help, especially for creating the code for the adapter/facade pattern classes.

  • Void Methods and Value Returning Methods in Java

    Hello,
    I'm new here so please let me know if I overstep any of the rules or expectations. I merely want to learn more about Java Programming efficiently, and easily. I can ask and discuss these topics with my online prof, but she doesn't have much time.
    So right now I'm trying to solve a problem. It's a typical college level computing problem which I've already turned in. So I'm not looking for someone to do my homework for me or something. It's just that the program didn't work. Even though I probably won't get a very good grade for it, I want to
    make it work! I'm kind of slow when it comes to java so just bear with me.
    The prof wanted us to write an algorithm that reads a student's name and 6 exam scores. Then it computes the average score for each student, assigns a letter grade, using a rating scale:
    90 and above = A
    80 - 89 = B
    70 ? 79 = C
    60 - 69 = D
    Less then 60 ? F
    We had to use a void method to determine the average score for each student, a loop inside the method to read the and sum the 6 scores but without outputting the average score. The sum and average had to be returned in and output in void main.
    Then we had to use a value-returning method CalculateGrade to determine and return the grade for each student. But it can't output the grade because that must be done in void main.
    Finally the class average must be output.
    Our prof gave us a list of student names with their 6 scores.
    Ward 100 54 98 65 35 100
    Burris 89 65 87 84 15 32
    Harris 54 21 55 87 70 54
    Bettis 43 55 68 54 15 25
    Staley 87 54 98 45 54 56
    Randle 54 87 54 98 65 15
    Maddox 56 14 40 50 40 50
    Roth 30 40 54 78 24 19
    Holmes 14 87 98 34 55 57
    So all the data had to be read from a file and the results output to a file. Also we couldn't use 'global variables'. We had to use the appropriate parameters to pass values to and from methods.
    Question 1:  What does she mean by 'no global variables'? Maybe she means: don't use "*double test1, test2, test3, test4, test5*;"
    Anyway because I'm a slow learner with Java, I end up looking for sample programs that seem to do a similar job as the problem posed. So with this program I decided to adapt a program called Comparison of Class Averages.
    //Program: Comparison of Class Averages.
    import java.io.*;
    import java.util.*;
    import java.text.DecimalFormat;
    public class DataComparison
    public static void main (String[] args) throws
    FileNotFoundException, IOException
    //Step 1
    String courseId1; //course ID for group 1
    String courseId2; //course ID for group 2
    int numberOfCourses;
    DoubleClass avg1 = new DoubleClass(); //average for a course
    //in group 1
    DoubleClass avg2 = new DoubleClass(); //average for a course
    //in group 2
    double avgGroup1; //average group 1
    double avgGroup2; //average group 2
    String inputGroup1;
    String inputGroup2;
    StringTokenizer tokenizer1 = null;
    StringTokenizer tokenizer2 = null;
    //Step 2 Open input and output files
    BufferedReader group1 =
    new BufferedReader(new FileReader("a:\\group1.txt"));
    BufferedReader group2 =
    new BufferedReader(new FileReader("a:\\group2.txt"));
    PrintWriter outfile =
    new PrintWriter(new FileWriter("a:\\student.out"));
    DecimalFormat twoDecimal =
    new DecimalFormat("0.00"); //Step 3
    avgGroup1 = 0.0; //Step 4
    avgGroup2 = 0.0; //Step 5
    numberOfCourses = 0; //Step 6
    //print heading: Step 7
    outfile.println("Course No Group No Course Average");
    inputGroup1 = group1.readLine(); //Step 8
    inputGroup2 = group2.readLine(); //Step 9
    while((inputGroup1 != null) &&
    (inputGroup2 != null)) //Step 10
    tokenizer1 = new StringTokenizer(inputGroup1);
    courseId1 = tokenizer1.nextToken(); //Step 10a
    tokenizer2 = new StringTokenizer(inputGroup2);
    courseId2 = tokenizer2.nextToken(); //Step 10b
    if(!courseId1.equals(courseId2)) //Step 10c
    System.out.println("Data error: Course IDs "
    + "do not match.");
    System.out.println("Program terminates.");
    outfile.println("Data error: Course IDs "
    + "do not match.");
    outfile.println("Program terminates.");
    outfile.close();
    return;
    else //Step 10d
    calculateAverage(group1, tokenizer1, avg1); //Step 10d.i
    calculateAverage(group2, tokenizer2, avg2); //Step 10d.ii
    printResult(outfile,courseId1,1,avg1); //Step 10d.iii
    printResult(outfile,courseId2,2,avg2); //Step 10d.iv
    avgGroup1 = avgGroup1 + avg1.getNum(); //Step 10d.v
    avgGroup2 = avgGroup2 + avg2.getNum(); //Step 10d.vi
    outfile.println();
    numberOfCourses++; //Step 10d.vii
    inputGroup1 = group1.readLine(); //Step 10e
    inputGroup2 = group2.readLine(); //Step 10f
    }//end while
    if((inputGroup1 != null) && (inputGroup2 == null)) //Step 11a
    System.out.println("Ran out of data for group 2 "
    + "before group 1.");
    else //Step 11b
    if((inputGroup1 == null) && (inputGroup1 != null))
    System.out.println("Ran out of data for "
    + "group 1 before group 2.");
    else //Step 11c
    outfile.println("Avg for group 1: " +
    twoDecimal.format(avgGroup1 / numberOfCourses));
    outfile.println("Avg for group 2: " +
    twoDecimal.format(avgGroup2 / numberOfCourses));
    outfile.close(); //Step 12
    public static void calculateAverage(BufferedReader inp,
    StringTokenizer tok,
    DoubleClass courseAvg)
    throws IOException
    double totalScore = 0.0;
    int numberOfStudents = 0;
    int score = 0;
    if(!tok.hasMoreTokens())
    tok = new StringTokenizer(inp.readLine());
    score = Integer.parseInt(tok.nextToken());
    while(score != -999)
    totalScore = totalScore + score;
    numberOfStudents++;
    if(!tok.hasMoreTokens())
    tok = new StringTokenizer(inp.readLine());
    score = Integer.parseInt(tok.nextToken());
    }//end while
    courseAvg.setNum(totalScore / numberOfStudents);
    }//end calculate Average
    public static void printResult(PrintWriter outp,
    String courseId,
    int groupNo, DoubleClass avg)
    DecimalFormat twoDecimal =
    new DecimalFormat("0.00");
    if(groupNo == 1)
    outp.print(" " + courseId + " ");
    else
    outp.print(" ");
    outp.println("\t" + groupNo + "\t "
    + twoDecimal.format(avg.getNum()));
    So my adaptation turned out like this:
    //Program: Compute individual and class averages from input file.
    import java.io.*;
    import java.util.*;
    public class Exams
    public static void main (String[] args)
    throws FileNotFoundException
    //Step 1
    String nameId; //student name ID for list
    int numberOfStudents;
    DoubleClass avg = new DoubleClass(); //average for a student
    //in list
    double avgList; //average for list
    //Step 2 Open the input and output files
    Scanner group1 = new Scanner(new FileReader("c:\\list.txt"));
    PrintWriter outfile = new PrintWriter("c:\\student.out");
    avgList = 0.0; //Step 3
    numberOfStudents = 0; //Step 5
    //print heading: Step 6
    outfile.println("NameID List Student Average");
    calculateAverage(list, avg); //Step 7d.i
    printResult(outfile,nameID, avg); //Step 7d.iii
    avgList = avgList + avgList.getNum(); //Step 7d.v
    outfile.println();
    numberOfStudents++; //Step 7d.vii
    outfile.printf("Avg for List: %.2f %n",
    (avgList / numberOfStudents));
    public static void calculateAverage(Scanner inp,
    DoubleClass courseAvg)
    double totalScore = 0.0;
    int numberOfStudents = 0;
    int score = 0;
    score = inp.nextInt();
    courseAvg.setNum(totalScore / numberOfStudents);
    }//end calculate Average
    public static void printResult(PrintWriter outp,
    String nameId,
    int groupNo, DoubleClass avg)
    if (list == list)
    outp.print(" " + nameId + " ");
    else
    outp.print(" ");
    outp.printf("%9d %15.2f%n", list, avg.getNum());
    I guess I was trying to find a shortcut that ended up being a long cut. Here's the algorithm I wrote.
    Algorithm
    1.) Initialize the variables
    2.) Get the student name and his/her accompanying 6 exam scores, limiting the number of scores to 6.
    3a.) Calculate score of 6 exams for each student using void method called CalculateAverage.
    3b.) Use a loop inside the method to read and sum the six scores.
    4.) Use value-returning method CalculateGrade to determine and return each student's grade.
    5.) Output each student's grade in void main.
    6.) Calculate the average score for all students
    7.) Output entire class average
    And now I'm trying to piece together code to match each step of the algorithm starting from scratch.
    So I got the code for outputting each students grade in void:
    public static void printGrade(double testScore)
    System.out.print("Line 10: Your grade for "
    + "the course is ");
    if (testScore >= 90)
    System.out.println("A");
    else if (testScore >= 80)
    System.out.println("B");
    else if (testScore >= 70)
    System.out.println("C");
    else if (testScore >= 60)
    System.out.println("D");
    else
    System.out.println("F");
    This code can read the the file with the scores:
    Scanner inFile =
    new Scanner(new FileReader("a:\\studentlist.txt"));
    PrintWriter outFile =
    new PrintWriter("a:\\avg.out");
    courseGrade = inFile.nextDouble();
    studentName=inFile.nextChar();
    while (inFile.hasNext())
    studentName= inFile.next().charAt(0);
    courseGrade= inFile.nextDouble();
    I'm just trying to piece this thing together. Any tips would be appreciated. I will return with more pieces to the puzzle soon. As you can tell it's all kind of disorganized, and scatterbrained. Just trying to find some simplification or distillation, or recommendations.
    WR

    Hello,
    Thanks for your reply. So I take it you are more familiar with Object Oriented Programming more than Procedural Based Programming?
    Well the teacher insisted I follow the algorithm instead of trying to adapt another program to the problem. But sometimes that approach saves time I've noticed since many of the code examples we study in Java are like 'the golden oldies'.
    The student gradebook problem is repeated over and over in different forms. Maybe if I just approached the problem more linearly:
    Algorithm
    1.) Initialize the variables
    String studentId
    int numberOfStudents
    DoubleClass avg = new DoubleClass(); //average for a student
    double avgGroup: //average for all students2.) Get the student name and his/her accompanying 6 exam scores.
    Scanner group = new Scanner(new FileReader("c:\\list.txt"));
    PrintWriter outfile = new PrintWriter("c:\\student.out"));
    3a.) Calculate score of 6 exams for each student using void method called CalculateAverage using a loop to read and sum the six scores. The loop must be inside the method. It does not output the average score. The sum and average must be returned and output in void main.
    method calculateAverage
    double totalScore //to store the sum of all the scores of each student
    int numberOfExams;  //to store the number of
    int score; //to read and store a course score
    double totalScore = 0.0
    int numberOfExams = 0;
    int score = 0;3b.) Use a loop inside the method to read and sum the six scores.
    Using psuedocode (since the variables have been declared and initialized)
    i)get the next student score
    RIght here my approach of adapting another program to my new program becomes problematic
    the pseudocode here is:
    ii) while (score != -999):
    I.) update totalScore by adding course score read in step i.
    II.) increment numberOfExams by 1
    III.) Get the nex student score
    iii) studentAvg.setNum(totalScore / numberOfExams);
    *What is the purpose of the statement while (score != -999)?*
    I don't see why they picked -999?  Will this loop allow me to read an endless number of student names and theri accompanying number of exams and then find the average for each student?
    I'll go into the next algorithmic steps later.
    4.) Use value-returning method CalculateGrade to determine and return each student's grade.
    5.) Output each student's grade in void main.
    6.) Calculate the average score for all students
    7.) Output entire class average
    Thanks ahead of time for any suggestions, tips.

  • AT Commands , Hyper Terminal and java

    Hi,
    I have following problem, i have PCMCIA Type -11 Wireless modem.its installed on my system COM4 port.
    Now first problem is that when i try to connect with hyper terminal to COM4 there is no response from it .It become Idle.but when i connect with COM3 which is my Dialup modem port it works fine with all AT commands.
    Now 2nd things is that same with below code i tried to send sms using AT command on COM4 its has same behaviour as it was in Hyper terminal mean no response. no Data Available event occour
    Please help me in this regard and suggest me a solution.
    package serialio;
    import javax.comm.*;
    import java.io.*;
    import java.util.*;
    public class SimpleWrite
        implements Runnable, SerialPortEventListener
      public void run()
      static Enumeration portList;
      static CommPortIdentifier portId;
      static String dest = "0517111930";
      static String messageString = "Hello";
      InputStream inputStream;
      static SerialPort serialPort;
      static OutputStream outputStream;
      public void serialEvent(SerialPortEvent event)
        switch (event.getEventType())
          case SerialPortEvent.BI:
          case SerialPortEvent.OE:
          case SerialPortEvent.FE:
          case SerialPortEvent.PE:
          case SerialPortEvent.CD:
          case SerialPortEvent.CTS:
          case SerialPortEvent.DSR:
          case SerialPortEvent.RI:
          case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            break;
          case SerialPortEvent.DATA_AVAILABLE:
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            try
              while ( (line = reader.readLine()) != null)
                System.out.println(line);
            catch (IOException e)
              System.err.println("Error while reading Port " + e);
            break;
        } //switch
      public SimpleWrite(SerialPort serial)
        try
          inputStream = serial.getInputStream();
          try
            serial.addEventListener(this);
          catch (TooManyListenersException e)
            System.out.println("Exception in Adding Listener" + e);
          serial.notifyOnDataAvailable(true);
        catch (Exception ex)
          System.out.println("Exception in getting InputStream" + ex);
      public static void main(String[] args)
    //    String line1="AT+CMGF=1\r\n";
    //    String line2="AT+CMGS=\""+ dest+"\"\r\n";
    //    String line3=messageString+"\r\n";
    //    String line4="\u001A";
        String line1 = "AT+CMGF=1\r\n";
        String line2 = "AT+CMGS=" + dest + "\r\n";
        String line3 = messageString + "^Z\r\n";
    //    String line4 = "\u001A";
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements())
          portId = (CommPortIdentifier) portList.nextElement();
          if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
            System.out.println("SMS Sending........");
            if ( portId.getName().equals("COM4"))
              System.out.println("SMS Sending....Port Found");
              try
                serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
                SimpleWrite wr = new SimpleWrite(serialPort);
              catch (PortInUseException e)
                System.out.println("Port In Use " + e);
              try
                outputStream = serialPort.getOutputStream();
              catch (IOException e)
                System.out.println("Error writing to output stream " + e);
              try
                serialPort.setSerialPortParams(
                    2400,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
              catch (UnsupportedCommOperationException e)
              try
                outputStream.write(line1.getBytes());
                outputStream.write(line2.getBytes());
                outputStream.write(line3.getBytes());
                outputStream.flush();
              catch (IOException e)
                System.out.println("Error writing message " + e);
      /** show text in the text window
       * @param Text text string to show on the display
      public static void showText(String Text)
        System.out.println(Text);
    }

    * SerialWrite.java
    * Created on September 10, 2008, 2:51 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.sms;
    import javax.comm.*;
    import java.io.*;
    import java.util.*;
    public class SerialWrite implements Runnable, SerialPortEventListener
    static String output="";
    public void run()
    static Enumeration portList;
    static CommPortIdentifier portId;
    static String dest = "+91999999999";
    static String messageString = "Hello Testing11";
    InputStream inputStream;
    static SerialPort serialPort;
    static OutputStream outputStream;
    public void serialEvent(SerialPortEvent event)
    switch (event.getEventType())
    case SerialPortEvent.BI:
    case SerialPortEvent.OE:
    case SerialPortEvent.FE:
    case SerialPortEvent.PE:
    case SerialPortEvent.CD:
    case SerialPortEvent.CTS:
    case SerialPortEvent.DSR:
    case SerialPortEvent.RI:
    case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
              System.out.println("Error");
    break;
    case SerialPortEvent.DATA_AVAILABLE:
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    try
    while ( (line = reader.readLine()) != null)
    if(line.equalsIgnoreCase("OK") || (line.indexOf("+CMGS") != -1))
         output=line;
              Thread.sleep(10);
    catch (Exception e)
    System.err.println("Error while reading Port " + e);
    break;
    } //switch
    public SerialWrite(SerialPort serial)
    try
    inputStream = serial.getInputStream();
    try
    serial.addEventListener(this);
    catch (TooManyListenersException e)
    System.out.println("Exception in Adding Listener" + e);
    serial.notifyOnDataAvailable(true);
    catch (Exception ex)
    System.out.println("Exception in getting InputStream" + ex);
    public static void main(String[] args) throws Exception
         int i=0;
    String line0 = "ATZ\r\n";
    String line1 = "AT+CMGF=1\r\n";
    String line2 = "AT+CSCA=\"+919888888\"\r\n";
    //String line3 = "AT+CMGS="+"\""+ dest + "\""+"\r\n";
    String line3 = "AT+CMGS="+"\""+ args[0] + "\""+"\r\n";
    //String line4 = messageString;
    String line4 = args[1];
         portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements())
    portId = (CommPortIdentifier) portList.nextElement();
    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
    System.out.println("SMS Sending........");
    if ( portId.getName().equals("/dev/ttyACM0"))
    System.out.println("SMS Sending....Port Found");
    try
    serialPort = (SerialPort) portId.open("SerialTestApp", 2000);
    SerialWrite wr = new SerialWrite(serialPort);
    catch (PortInUseException e)
    System.out.println("Port In Use " + e);
    try
    outputStream = serialPort.getOutputStream();
    catch (IOException e)
    System.out.println("Error writing to output stream " + e);
    try
    serialPort.setSerialPortParams(
    115200,
    SerialPort.DATABITS_8,
    SerialPort.STOPBITS_1,
    SerialPort.PARITY_NONE);
    catch (UnsupportedCommOperationException e)
    try
    outputStream.write(line0.getBytes());
              Thread.sleep(10);
    while(!output.equalsIgnoreCase("ok"))
              Thread.sleep(10);
              output="";
    outputStream.write(line1.getBytes());
    while(!output.equalsIgnoreCase("ok"))
                   Thread.sleep(10);
              output="";
    outputStream.write(line2.getBytes());
    while(!output.equalsIgnoreCase("ok"))
                   Thread.sleep(10);
              output="";
         for(i=0;i<3;i++)
    outputStream.write(line3.getBytes());
    Thread.sleep(10);
    outputStream.write(line4.getBytes());
    Thread.sleep(10);
    outputStream.write(26);
    outputStream.write("\r\n".getBytes());
    outputStream.flush();
    while(!output.equalsIgnoreCase("ok"))
                   Thread.sleep(10);
              output="";
              System.out.println("Message Sent !!!!!!!!!1");
    catch (IOException e)
    System.out.println("Error writing message " + e);
    /** show text in the text window
    * @param Text text string to show on the display
    public static void showText(String Text)
    System.out.println("TEXT "+Text);
    }

  • Sending email using SMTP and Java

    Hi guys
    I am using the following code to send an email:
    private void sendEmail(String mDate, String time) {       
            Date date = new Date();
            DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, Locale.ENGLISH);
            // Open port to server
            try {
              smtpSocket = new Socket(SMTP_SERVER, SMTP_PORT);
              os = new DataOutputStream(smtpSocket.getOutputStream());
              is = new DataInputStream(smtpSocket.getInputStream());
              // Connection was made.  Socket is ready for use.
              if(smtpSocket != null && os != null && is != null) {
                try {
                    // email header
                    os.writeBytes("HELO\r\n");
                    // set the reply email address
                    os.writeBytes("MAIL From: <[email protected]>\r\n");
                    // give the address of the people that we want the email sent to
                    for(int i=0; i<RECIPIENTS.length; i++) {
                        os.writeBytes("RCPT To: <" + RECIPIENTS[i] + ">\r\n");
                        System.out.println(RECIPIENTS);
    // data header
    os.writeBytes("DATA\r\n");
    os.writeBytes("X-Mailer: Via Java\r\n");
    os.writeBytes("DATE: " + dateFormat.format(date) + "\r\n");
    os.writeBytes("From: Characterisation System Update\r\n");
    os.writeBytes("Mime-Version: 1.0\r\n");
    os.writeBytes("Content-Type: text/html; charset=\"ISO-8859-1\"\r\n");
    //os.writeBytes("Content-Transfer-Encoding: 7bit;\r\n");
    for(int i=0; i<RECIPIENTS.length; i++) {
    os.writeBytes("To: <" + RECIPIENTS[i] + ">\r\n");
    // get the details of the test and enter them into the message body
    String message = "<HTML><BODY>" +
    "\r\nThe following System has not received a data packet for at leat 1 hour:" +
    "\r\n<BR/><BR/><B>System:</B> " + rackName +
    "\r\n<BR/><B>Time Last Pkt. Received:</B> " + time +
    "\r\n<BR/><B>Date Last Pkt. Received:</B> " + mDate +
    "\r\n<BR/><B>Job Number:</B> " + jobNoDispLabel.getText() +
    "\r\n<BR/><B>Device:</B> " + deviceDispLabel.getText() +
    "\r\n<BR/><B>Run Number:</B> " + runNoDispLabel.getText() +
    "\r\n<BR/><B>Current Temperature:</B> " + tempDispLabel.getText() +
    "\r\n<BR/><B>Current Module:</B> " + moduleDispLabel.getText() +
    "\r\n<BR/><B>Current Test:</B> " + testingDispLabel.getText() +
    "\r\n<BR/><BR/>This does not gurantee that the system has crashed!" +
    "\r\n</BODY></HTML>";
    os.writeBytes("Subject: " + rackName + " Packet Warning\r\n");
    os.writeBytes(message + "\r\n");
    os.writeBytes("\r\n.\r\n");
    os.writeBytes("QUIT\r\n");
    // Now send the email off and check the server reply.
    // Was an OK is reached you are complete.
    String responseline;
    //DataInputStream d = new DataInputStream(is);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    while((responseline = reader.readLine())!= null) { 
    if(responseline.indexOf("Ok") != -1) {
    break;
    } catch(Exception e) {
    System.out.println("Cannot send email as an error occurred.");
    e.printStackTrace();
    catch(Exception e) {
    System.out.println("Host " + SMTP_SERVER + "unknown");
    e.printStackTrace();
    } finally {
    // close all of the data streams
    try {
    if(!smtpSocket.isClosed()) {
    smtpSocket.close();
    smtpSocket = null;
    } catch(Exception e) {
    e.printStackTrace();
    try {
    if(os != null) {
    os.close();
    os = null;
    } catch(Exception e) {
    e.printStackTrace();
    try {
    if(is != null) {
    is.close();
    is = null;
    } catch(Exception e) {
    e.printStackTrace();
    i have used an example on the web to help me do this, so it may look familiar!!
    It works fine when i run the program in debug mode but doesn't work when i run the jar file, i was wondering if anyone could help me understand why? or give me a clue as to where to look as i have had the strange realisation that i rarely compile my code up to be used by other people!!
    sad but true! Also apologies if i haven't posted adequate information, this is the first time i have posted on the forum asking for help!
    Anyway help would be most appreciated and thanks in advance

    Sorry, by debug mode i mean running it using netbeans 5.5 and clicking on the "run main project" icon.
    Once i have cleaned and built the main project all of the files are put into the jar file. Once i have done that i double click on the jar icon
    is that ok? there doesn't seem to be any errors

  • Sending Email using java code

    I am using the following code to send an email from my java servlet but the problem is, when it is on its own it works fine but as soon as I combine it with some code to submit data into a postgres database it sometimes does not perform could it be because im missing some close statements??
    //grades to submit grades starts here
                                                           String [] paramValues = req.getParameterValues("Mark");
                                                      for(int i=0; i<paramValues.length;i++)
                                                           String [] paramValues2 = req.getParameterValues("StudentExamNumber");
                                                                String Mark = paramValues;
                                                                String ExamNo = paramValues2[i];
                                                                //testing purposes
                                                                out.println("<tr><td>"+ExamNo+"</td>");
                                                                out.println("<td>"+Mark+"</td>");
                                                                try
                                                           st = conn.createStatement();
                                                           query = "SELECT StudentNo FROM STUDENTS"+WebCourse2+ " where ExamNo='"+ExamNo+"'";
                                                           rs = st.executeQuery(query);
                                                           if(rs !=null)
                                                                          while(rs.next())
                                                                               String StudentNo=rs.getString("StudentNo");
                                                                               //testing purposes
                                                                               //out.println("<td>"+StudentNo+"</td></tr>");
                                                                               here
                                                                               st4 = conn.createStatement();
                                                                     query4 = "select MAX(entryno) from STUDENTRESULTSFORCOURSE"+WebCourse2+" WHERE STUDENTNO='"+StudentNo+"'";
                                                                     rs4 = st4.executeQuery(query4);
                                                                     if(rs4 !=null)
                                                                                    while(rs4.next())
                                                                                         EntryNo = rs4.getInt(1);
                                                                                    }//end rs4 while
                                                                                    rs4.close();
                                                                               }//end rs4 if
                                                                     out.println("<tr><td>EntryNo= "+EntryNo+"</td>");
                                                                               EntryNo = EntryNo + 1;
                                                                               out.println("<td>NewEntryNo= "+EntryNo+"</td></tr>");
                                                                               //Submitting grades to database/
                                                                     st3 = conn.createStatement();
                                                                     insert = "insert into STUDENTRESULTSFORCOURSE"+WebCourse2+" (StudentNo, CourseCode, AttemptNo, ExamMark, EntryNo, EnteredBy) values ('"+StudentNo+"', '"+WebCourse2+"', 1,'"+Mark+"',"+EntryNo+",'"+WebUsername2+"')";
                                                                     st3.executeUpdate(insert);
                                                                          }//end rs while
                                                                          rs.close();
                                                                     }//end rs if
                                                                }//end try
                                                                catch (SQLException e)
                                                                     System.out.println("Error: "+e.getMessage());
                                                           }//end for loop     
                                                           //code to submit grades ends here
                                                           //code used to send email starts here
                                                           String m_sHostName="localhost";
                                                      int m_iPort=25;
                                                           try
                                                                // Open port to server
                                                                smtpSocket = new Socket(m_sHostName, m_iPort);
                                                                os = new DataOutputStream(smtpSocket.getOutputStream());
                                                                is = new DataInputStream(smtpSocket.getInputStream());
                                                                if(smtpSocket != null && os != null && is != null)
                                                                     // Connection was made. Socket is ready for use.
                                                                     System.out.println("Connection was made. Socket is ready for use.");
                                                                     try
                                                                          // The email address that the server
                                                                          // you are using know user as.
                                                                          os.writeBytes("MAIL From: <[email protected]>\r\n");
                                                                          // Who the email is going to.
                                                                          os.writeBytes("RCPT To: <[email protected]>\r\n");
                                                                          //send a CC to:
                                                                          os.writeBytes("RCPT Cc: <[email protected]>\r\n");
                                                                          // add the message and the
                                                                          // header of the email to be sent out.
                                                                          os.writeBytes("DATA\r\n");
                                                                          os.writeBytes("X-Mailer: Via Java\r\n");
                                                                          os.writeBytes("From: "+WebUsername2+"<[email protected]>\r\n");
                                                                          os.writeBytes("To: Marie <[email protected]>\r\n");
                                                                          //Again if you want to send a CC then add this.
                                                                          os.writeBytes("Cc: ProfCuthbert <[email protected]>\r\n");
                                                                          String sMessage = "ELECTRONIC ENGINEERING EXAM COLLATION SYSTEM EMAIL\n\nThe results for the following course have been submitted by the following member of staff\n\nCOURSE: "+WebCourse2+"\n\nSUBMITTED BY: "+WebUsername2+" \n\nPLEASE LOCK COURSE NOW IN ORDER TO PREVENT ANY FURTHER SUBMISSIONS TO BE MADE BY USERS.";
                                                                          os.writeBytes("Subject: A SUBMISSION HAS BEEN MADE FOR COURSE "+WebCourse2+"\r\n");
                                                                          os.writeBytes(sMessage + "\r\n");
                                                                          os.writeBytes("\r\n.\r\n");
                                                                          os.writeBytes("QUIT\r\n");
                                                                          // Now send the email off and check the server reply.
                                                                          // Once an OK is reached you are complete.
                                                                          String responseline;
                                                                          //for testing purposes
                                                                          //out.println(responseline = is.readLine());
                                                                          while((responseline = is.readLine())!=null)
                                                                          //for testing purposes
                                                                          //out.println("responseline= "+responseline+"<br>");
                                                                          //out.println("responseline.indexOf(Ok)= "+responseline.indexOf("Ok"));
                                                                          if(responseline.indexOf("Ok") != -1)
                                                                          break;
                                                                          if(responseline.indexOf("Ok") == -1)
                                                                          confirm=1;
                                                                          if (confirm==1)
                                                                          out.println("<br>the marks have been submitted thank you");
                                                                          catch(Exception e)
                                                                          {  System.out.println("Cannot send email as an error occurred.");
                                                                               out.println("Cannot send email as an error occurred.");
                                                           catch(Exception e)
                                                           { System.out.println("Host " + m_sHostName + "unknown"); }
    Does anyone know what the problem is??
    thanks
    tzaf

    i close them later in the program. Ive made sure they are all closed I have a feeling that it could be coming from here....
    //code used to send email starts here
                                                           String m_sHostName="localhost";
                                                      int m_iPort=25;
                                                           try
                                                                // Open port to server
                                                                smtpSocket = new Socket(m_sHostName, m_iPort);
                                                                os = new DataOutputStream(smtpSocket.getOutputStream());
                                                                is = new DataInputStream(smtpSocket.getInputStream());
                                                                if(smtpSocket != null && os != null && is != null)
                                                                     // Connection was made. Socket is ready for use.
                                                                     System.out.println("Connection was made. Socket is ready for use.");
                                                                     try
                                                                          // The email address that the server
                                                                          // you are using know user as.
                                                                          os.writeBytes("MAIL From: <email address>\r\n");
                                                                          // Who the email is going to.
                                                                          os.writeBytes("RCPT To: <email address>\r\n");
                                                                          //send a CC to:
                                                                          os.writeBytes("RCPT Cc: <email address>\r\n");
                                                                          // add the message and the
                                                                          // header of the email to be sent out.
                                                                          os.writeBytes("DATA\r\n");
                                                                          os.writeBytes("X-Mailer: Via Java\r\n");
                                                                          os.writeBytes("From: "+WebUsername2+"<email address>\r\n");
                                                                          os.writeBytes("To: hello<email address>\r\n");
                                                                          //Again if you want to send a CC then add this.
                                                                          os.writeBytes("Cc: hello <email address>\r\n");
                                                                          String sMessage = "ELECTRONIC ENGINEERING EXAM COLLATION SYSTEM EMAIL\n\nThe results for the following course have been submitted by the following member of staff\n\nCOURSE: "+WebCourse2+"\n\nSUBMITTED BY: "+WebUsername2+" \n\nPLEASE LOCK COURSE NOW IN ORDER TO PREVENT ANY FURTHER SUBMISSIONS TO BE MADE BY USERS.";
                                                                          os.writeBytes("Subject: A SUBMISSION HAS BEEN MADE FOR COURSE "+WebCourse2+"\r\n");
                                                                          os.writeBytes(sMessage + "\r\n");
                                                                          os.writeBytes("\r\n.\r\n");
                                                                          os.writeBytes("QUIT\r\n");
                                                                          // Now send the email off and check the server reply.
                                                                          // Once an OK is reached you are complete.
                                                                          String responseline;
                                                                          //for testing purposes
                                                                          //out.println(responseline = is.readLine());
                                                                          while((responseline = is.readLine())!=null)
                                                                          //for testing purposes
                                                                          //out.println("responseline= "+responseline+"<br>");
                                                                          //out.println("responseline.indexOf(Ok)= "+responseline.indexOf("Ok"));
                                                                          if(responseline.indexOf("Ok") != -1)
                                                                          break;
                                                                          if(responseline.indexOf("Ok") == -1)
                                                                          confirm=1;
                                                                          if (confirm==1)
                                                                          out.println("<br>the marks have been submitted thank you");
                                                                          catch(Exception e)
                                                                          {  System.out.println("Cannot send email as an error occurred.");
                                                                               out.println("Cannot send email as an error occurred.");
                                                           catch(Exception e)
                                                           { System.out.println("Host " + m_sHostName + "unknown"); }
                                                           //code used to send email ends here
    do i need to close is and os?
    thanks
    tzaf

Maybe you are looking for

  • Unable to Open Images in Bridge CS3 and Continuing Icon issues!

    Re: Icon issues in Bridge CS3 and also with Photo Downloader that have never been there before.      So, these are the issues.   Just one of the folders that previously would show thumbnails now only shows DNG icons, and none will open in Photoshop t

  • Overriding function keys when using MS Remote Desktop Connection

    Is there a way when connected to a RDP client using MS Remote Desktop Connection to prevent the function keys from being intercepted and handled by OSX. For example on my iMac keyboard, function keys 7 to 12 are used to control itunes and alter the s

  • Contact Sheet II question

    I'm running CS3 and make contact sheets for weddings. 50 to 100 8.5x11 sheets is typical. Is there a way to get CS3 to save and close each contact sheet after its made, rather than leaving it as an open document on the desktop. It's a pain to have to

  • Disabling Horizontal Scroll in Mountain Lion (Magic Mouse)?

    So I've tried pretty much everything and can't seem to this. The following things used to work under Lion and before, it seems but having tried all of them, I'm at a loss for what to do. I like the magic mouse, but when doing any development like cod

  • Can't install After Effects for 2 months. No help from Adobe.

    I am tired of the complete disregard Adobe shows to its customers. I can't install After Effects. All other apps do install.