FileReader (?) problem

I'm not sure wether this is a problem with the FileReader or Internet Explorer but as other applications seem to have no problems I tend to think its Java.
Anyway, I'm trying to read in a web page, that was saved from the browser, as a String in Java. To do this I'm using the 'FileReader' class but it seems the FileReader has some problems with webpages saved from IE (no problems with Firefox pages though).
Using this code:
try {
     char[] buffer = new char[1024];
     FileReader r = new FileReader(new File("form_ie.html"));
     String result = "";
     while(true) {
          int num = r.read(buffer);
          if(num <= 0) break;
          result += new String(buffer,0,num);
     System.out.println(result);
catch(Exception ex) {
     ex.printStackTrace();
}The result is two strange characters at the start and then every two characters has value (as byte) of 0. Opening this site in notepad/firefox/ie/... gives no problems. Any idea what causes this and what can I do about it? (I'm currently removing char's with a byte value <=0)
The webpage I'm testing can be found on: http://student.kuleuven.be/~s0109731/Rommel/ under the filename "form_ie.html". This webpage was generated using Javascript so there might be no problems for regular webpages.
Now after reading in this webpage, I extract the internal xml block. This xml block is send to a SAXParser but as this SAXParser only accepts InputStreams, I need to turn a String into an InputStream. I found the java.io.StringBufferInputStream class but its deprecated and I can't find an alternative to turn a String into an InputStream. Any suggestions?

It's not generally possible to detect the encoding, no. Some specific patterns (like the byte order marks) might hint at an encoding (in this case UTF-16 - I really didn't mean UTF-8 earlier!), but they would also be perfectly valid characters if the stream were ISO-8859-1 encoded.
XML documents tell you there encoding (in the ?xml processing instruction) - of course, parsers have to do a bit of work to figure out what the byte encoding is before they can read the characters, but given that they're looking for specific patterns, that's pretty straightforward.
HTML documents generally don't self-identify. XHTML documents can (because they're XML). So, for HTML, the web-server normally tells you the character encoding in an HTTP header. But of course, you've already lost this information.
The reasons this is working if saved in FireFox and not IE, is that I expect IE is just saving out what it received whereas FireFox will be translating to your platform's default encoding where possible.
As to your other question, StringBufferInputStream is indeed deprecated in favour of StringReader. But as you said, XML parsers need byte streams, not readers full of characters (because they want to do their own decoding according to the XML PI).
Sun's silly forum software only lets you see the message you are replying to, not the whole thread, so I don't know what you were originally after, but notice that SAXParser also has parse() methods that take Files and InputSources. These may help. Note that an InputSource can be constructed from a Reader (but it mustn't contain a BOM which we've already decided you have).
Also, why read the file into a String? Why not read it into a byte array? This would be the preferred way of dealing with XML. Then you could make a ByteArrayInputStream from the byte[], and wrap that in an InputSource and you aren't mucking with any character encoding stuff outside of the XML.

Similar Messages

  • Filereader problems

    I would like to know how I can read filenames and also all of the subfolders in a directory into a database. I need this code for a CD-indexer so that I can find all the files on a specific cd. Currently, I'm having troubles reading the subfolders.

    You can list the contents of a directory using the File.list() method. If you pass a FileFilter as a parameter you can restrict the listing to include only certains types of files, like .mp3's and subdirectories.
    The API documentation of FIle has the full information:
    http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html

  • Orderbooking: FileRead Adapter problem

    Hi,
    Im currently having problems getting through the tutorial chapter 8. Im trying to implement the File Adapter functionality to read the xml files. Everything goed OK with compiling and deploying. But when i open the dashboard and try to check out the process it gives this error:
    Error Message:
    Cannot find partnerLinkType 2. PartnerLinkType "{http://xmlns.oracle.com/pcbpel/adapter/file/FileRead/}Read_plt" is not found in WSDL at "http://WP200011-001:9700/orabpel/default/BatchOrderProcessing/1.0/_BatchOrderProcessing.wsdl". Please make sure the partnerLinkType is defined in the WSDL.
    I tried to rebuild the workflow several times watching if i have forgotten something but it wasnt. I tried to use logical directories instead of Physical but none of those solutions worked.
    Note is that i run my BPEL server on an external machine cuase its very resource demanding. The physical directories are of course also available on the server. My workstation is running XP and the deploy server windows 2000.
    Does anyone knows how to solve this? thnx

    Welcome to Apple Discussions!
    It sounds like you may have a faulty DC IN Board. One end of the DC In Board is where you plug in your power adaptor, and your description of your problem sounds like this is where the damage is. Replacing the DC In board is not too bad to do. To see what it looks like and what is involved, go to:
    http://www.ifixit.com
    Look up your exact iBook and the DC In Board and you will find a picture of the the DC In Board and a detailed description of how to replace it. You could do the work yourself or have it done by a qualified repair shop. You may also need a new power adaptor--it could also be damaged from your description, but I'm not sure about that. Sparks are not a good sign.
    Good luck!

  • Using FileReader/Writer with Asian Characters - can you spot my problem?

    Hi,
    I can read in and write out one byte at a time with Asian characters, but if I try to do it one line at a time the Asian output is garbage. I will list both little programs here, and hopefully someone can educate me on my problem.
    +++1st, *this {color:#339966}works fine{color} with Asian characters:*+
    +{color:#000000}import java.io.*;*{color}+
    {color:#000000}class copybyte
    public static void main (String args[]) throws IOException
    if (args.length != 2)
    System.out.println("Usage: java copybyte srcfile dstfile");
    return;
    final boolean DEBUG=true; // switch for ascii display
    int ch; // the buffer{color}
    {color:#000000}// Create streams
    FileInputStream fis = new FileInputStream (args[0]);
    FileOutputStream fos = new FileOutputStream (args[1]);{color}
    {color:#000000}while ((ch = fis.read()) != -1)
    fos.write(ch);
    if (DEBUG)
    System.out.print(ch);
    System.out.println(" "+Character.toString((char)ch));
    fis.close(); fos.close();
    }{color}
    But the following code outputs Asian characters in garbage to my text file:
    {color:#000000}import java.io.;
    // Does not seem to handle Japanese....
    class CopyLineIO
    public static void main (String args[]) throws IOException
    if (args.length != 2)
    System.out.println("Usage: java copyline srcfile dstfile");
    return;
    final boolean STRIP=true; //strip blank lines from file ??
    String buf,temp;
    // Create streams
    FileReader fr = new FileReader (args[0]);
    FileWriter fw = new FileWriter (args[1]);
    BufferedReader br=new BufferedReader(fr); //wrap basic object
    BufferedWriter bw=new BufferedWriter(fw); //wrap basic object
    while ((buf = br.readLine()) != null)
    temp=buf.trim();
    if ((temp.length()>0)||(!STRIP)) {bw.write(buf"\n");}
    br.close(); bw.close();
    fr.close(); fw.close();
    Can anyone advise on what to change in CopyLineIO so that Asian characters work?{color} Thanks!
    PS Sorry about the code formatting - not sure how to get it looking decent here when pasted in....
    Edited by: JavaNeo on Jan 14, 2010 7:10 AM

    [From the documentation|http://java.sun.com/javase/6/docs/api/java/io/FileReader.html]:
    Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream. To post code use { code } // your code here { code } without the spaces or simple select the code and press the CODE button.
    // your code here

  • Strange problem with FileReader... stops applet from continuing...

    This has been bothering me for a few hours now.
    At a point in an applet I call FileReader and my applet stops. It doesn't freeze, I can still enter data but it will not go past this point in the program. I've set up displays before and after the specific statement fr = new FileReader("hash826923.dat"); and it stops right here. The little snippit goes as follows...
    FileReader fr;
               fr = new FileReader("hash826923.dat");
               hash.setText("after FR in OIF");
              fileIn = new BufferedReader(fr);
            hash.setText("after BR in OIF");The hash.setText's are my displays to a field called hash. Any display to hash before the FileReader call is displayed. After it is not.
    Anyone seen this problem?
    Thanks

    This has been bothering me for a few hours now.
    At a point in an applet I call FileReader and my
    applet stops. It doesn't freeze, I can still enter
    data but it will not go past this point in the
    program. I've set up displays before and after the
    specific statement fr = new
    FileReader("hash826923.dat"); and it stops
    right here. The little snippit goes as follows...
    FileReader fr;
         fr = new FileReader("hash826923.dat");
         hash.setText("after FR in OIF");
              fileIn = new BufferedReader(fr);
    hash.setText("after BR in OIF");The hash.setText's are my displays to a
    field called hash. Any display to hash before the
    FileReader call is displayed. After it is not.
    Anyone seen this problem?
    ThanksSend the rest of the code because where is fileIn declared to be a BufferedReader?

  • New to java...  Having problems with Stringbuffer - FileReader

    I believe what I am trying to do is quite simple but I am missing something...
    Basically I need to read the contents of a text file and append the text to an email message. As I said, I am new to java and I certainly don't understand everything, but I will do my best to answer any questions you may have.
    My attempt at writing the code is below. The relevant sections are in bold
    private void emailDevLicense(HttpServletRequest request, HttpServletResponse response, String operatorId) {
    String configId = request.getParameter("configurationId");
    String deployPath = cdlcmConfig.getLmLicensePath();
    String cName = request.getParameter("cName");
    String aName = request.getParameter("aName");
    String lPath = request.getParameter("lPath");
    String licenseName = request.getParameter("name");
    String description = request.getParameter("licenseConfigDesc");
    String contents = null;
    Properties emailProperties = new Properties();
    emailProperties.put("mail.smtp.host", cdlcmConfig.getEmsMailServer());
    Session mailSession = Session.getDefaultInstance(emailProperties, null);
    String mailFrom = cdlcmConfig.getEmsMailFrom();
    MimeMessage message = new MimeMessage(mailSession);
    MimeBodyPart p1 = new MimeBodyPart();
    MimeBodyPart p2 = new MimeBodyPart();
    MimeBodyPart p3 = new MimeBodyPart();
    String operatorName = DbHelper.getOperatorName(operatorId);
    String recipient = "[email protected]";
    String filename1 = deployPath + "/l-" + configId + "/license.dat";
    String filename2 = deployPath + "/l-" + configId + "/company.dat";
    log.info("emailDevLicense");
    *try {*
    File f = new File(lPath, "license.dat");
    BufferedReader br = new BufferedReader(new FileReader(f));
    StringBuffer sb = new StringBuffer();
    String eachLine = br.readLine();
    *while (eachLine != null) {*
    eachLine = br.readLine();
    sb.append(contents); }
    *catch (java.io.FileNotFoundException ex) {*
    log.error("Unable to find license file license.dat", ex);
    *catch (java.io.IOException ex) {*
    log.error("Unable to read lines from license.dat", ex);
    try {
    /* Set user-entered RFC822 headers to a message (mmsg). */
    message.setHeader ("From", "[email protected]");
    message.setHeader ("Reply-To", "[email protected]");
    message.setHeader ("To", recipient);
    message.setSubject("License files for Customer Name: " + cName + " / Account Name: " + aName + "");
    /* Add any other desired headers. */
    p1.setText("Configuration Name: " + licenseName + "\n\nOrder Number: " + description + "" + contents + "");
    // Put a file in the second part
    FileDataSource fds1 = new FileDataSource(filename1);
    p2.setDataHandler(new DataHandler(fds1));
    p2.setFileName(fds1.getName());
    // Put a file in the second part
    FileDataSource fds2 = new FileDataSource(filename2);
    p3.setDataHandler(new DataHandler(fds2));
    p3.setFileName(fds2.getName());
    // Create the Multipart. Add BodyParts to it.
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(p1);
    mp.addBodyPart(p2);
    mp.addBodyPart(p3);
    // Set Multipart as the message's content
    message.setContent(mp);
    log.info("Sending Dev License");
    Transport.send(message);
    } catch (MessagingException ex) {
    log.error("Unable to send license mail to address " + recipient, ex);
    }

    You guys\gals rock...
    This solved my problem and taught me something in the process. I have been trying to do this myself for 3 days now...so...thanks so much for the help.
    Once that worked I had to add a return after each line was read and I actually got that right on the first try.
    The final code is below.
    Thanks everyone..
    try {
                File f = new File(lPath, "license.dat");
                BufferedReader br = new BufferedReader(new FileReader(f));
                StringBuffer sb = new StringBuffer();
                String eachLine = br.readLine();
                while (eachLine != null) {
                    sb.append(eachLine + "\n");
                    eachLine = br.readLine();
               contents = sb.toString();
                catch (java.io.FileNotFoundException ex) {
                log.error("Unable to find license file license.dat", ex);
                catch (java.io.IOException ex) {
                log.error("Unable to read lines from license.dat", ex);
                }

  • Problem with PDFBox-0.7.3 library - Runtime Error

    Hello,
    The problem is inside the method "chamaConversor".
    " conversor.pdfToText(arquivoPdf,arquivoTxt);" make a file.txt from one file.pdf. After that it don?t return the control to "ConstrutorDeTemplate2.java", and show the following error message:
    Exception in thread "AWT-EventQueue-O" java.lang.NoClassDefFoundError : org/fontbox/afm/FontMetric
    at org.pdfbox.pdmodel.font.PDFont.getAFM (PDFont.java:334)
    I am using the NetBeans IDE 5.5.
    I have added all of these libraries below to my project from c:\Program Files\netbeans-5.5\PDFBox-0.7.3\external:
    * FontBox-0.1.0-dev.jar
    * ant.jar
    * bcmail-jdk14-132.jar
    * junit.jar
    * bcprov-jdk14-132.jar
    * lucene-core-2.0.0.jar
    * checkstyle-all-4.2.jar
    * lucene-demos-2.0.0.jar
    and PDFBox-0.7.3.jar from c:\Program Files\netbeans-5.5\PDFBox-0.7.3\lib.
    There are no more jar from PDFBox-0.7.3 directory.
    All of these libraries are in "Compile-time Libraries" option in Project Properties. Should I add they to "Run-time Libraries" option?
    What is going on?
    Thank you!
      * ConstrutorDeTemplate2.java
      * Created on 11 de Agosto de 2007, 14:54
      * @author
    package br.unifacs.dis2007.template2;
    // Java core packages
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.*;
    import java.util.*;
    // Java extension packages
    import javax.swing.*;
    import org.pdfbox.*;
    public class ConstrutorDeTemplate2 extends JFrame
        implements ActionListener {
        private JTextField enterField;
        private JTextArea outputArea;
        private BufferedWriter out;
        private String word;
        private PdfToText conversor = new PdfToText();
        // ajusta a interface do usu?rio
        public ConstrutorDeTemplate2()
           super( "Testing class File" );
           enterField = new JTextField("Digite aqui o nome do arquivo :" );
           enterField.addActionListener( this );
           outputArea = new JTextArea();
           ScrollPane scrollPane = new ScrollPane();
           scrollPane.add( outputArea );
           Container container = getContentPane();
           container.add( enterField, BorderLayout.NORTH );
           container.add( scrollPane, BorderLayout.CENTER );
           setSize( 400, 400 );
           show();
        // Exibe as informa??es sobre o arquivo especificado pelo usu?rio
        public void actionPerformed( ActionEvent actionEvent )
           File name = new File( actionEvent.getActionCommand() );
           // Se o arquivo existe, envia para a sa?da as informa??es sobre ele
           if ( name.exists() ) {
              outputArea.setText(
                 name.getName() + " exists\n" +
                 ( name.isFile () ?
                    "is a file\n" : "is not a file\n" ) +
                 ( name.isDirectory() ?
                    "is a directory\n" : "is not a directory\n" ) +
                 ( name.isAbsolute() ? "is absolute path\n" :
                    "is not absolute path\n" ) +
                 "Last modified: " + name.lastModified() +
                 "\nLength: " + name.length () +
                 "\nPath: " + name.getPath() +
                 "\nAbsolute path: " + name.getAbsolutePath() +
                 "\nParent: " + name.getParent() );
              // informa??o de sa?da se "name" ? um arquivo
              if ( name.isFile() ) {
                 String nameString = String.valueOf(name.getPath());
                 String nameTeste = new String(nameString);
                 if (nameString.endsWith(".pdf"))
                     nameTeste = chamaConversor(nameString);
                 else
                     if (nameString.endsWith(".doc"))
                         nameTeste = chamaConversorDoc(nameString); // chama conversor de arquivos DOC
                     else
                         if (nameString.endsWith(".txt"))
                             nameTeste = nameString;
                 // se o arquivo termina com ".txt"           
                 if (nameTeste.endsWith(".txt"))
                     // acrescenta conte?do do arquivo ? ?rea de sa?da
                     try {
                         // Create the tokenizer to read from a file
                         FileReader rd = new FileReader(nameTeste);
                         StreamTokenizer st = new StreamTokenizer(rd);
                         // Prepare the tokenizer for Java-style tokenizing rules
                         st.parseNumbers();
                         st.wordChars('_', '_');
                         st.eolIsSignificant (true);
                         // If whitespace is not to be discarded, make this call
                         st.ordinaryChars(0, ' ');
                         // These calls caused comments to be discarded
                         st.slashSlashComments(true);
                         st.slashStarComments(true);
                         // Parse the file
                         int token = st.nextToken();
                         String word_ant = "";
                         outputArea.append( " \n" );
                         out = new BufferedWriter(new FileWriter(nameTeste, true));
                         while (token != StreamTokenizer.TT_EOF) {
                             token = st.nextToken();
                             if (token == StreamTokenizer.TT_EOL){
                                 //out.write(word);
                                 out.flush();
                                 out = new BufferedWriter(new FileWriter(nameTeste, true));
                                 //outputArea.append( word + "\n" );
                                 // out.append ( "\n" );
                             switch (token) {
                             case StreamTokenizer.TT_NUMBER:
                                 // A number was found; the value is in nval
                                 double num = st.nval;
                                 break;
                             case StreamTokenizer.TT_WORD:
                                 // A word was found; the value is in sval
                                 word = st.sval;
                                 //   if (word_ant.equals("a") || word_ant.equals("an") || word_ant.equals("the") || word_ant.equals("The") || word_ant.equals("An"))
                                 outputArea.append( word.toString() + " \n " );
                                // out.append( word + "   " );
                                 //     word_ant = word;
                                 break;
                             case '"':
                                 // A double-quoted string was found; sval contains the contents
                                 String dquoteVal = st.sval;
                                 break;
                             case '\'':
                                 // A single-quoted string was found; sval contains the contents
                                 String squoteVal = st.sval;
                                 break;
                             case StreamTokenizer.TT_EOL:
                                 // End of line character found
                                 break;
                             case StreamTokenizer.TT_EOF:
                                 // End of file has been reached
                                 break;
                             default:
                                 // A regular character was found; the value is the token itself
                                 char ch = (char)st.ttype;
                                 break;
                             } // fim do switch
                         } // fim do while
                         rd.close();
                         out.close();
                     } // fim do try
                     // process file processing problems
                     catch( IOException ioException ) {
                         JOptionPane.showMessageDialog( this,
                         "FILE ERROR",
                         "FILE ERROR", JOptionPane.ERROR_MESSAGE );
                 } // fim do if da linha 92 - testa se o arquivo ? do tipo texto
              } // fim do if da linha 78 - testa se ? um arquivo
              // output directory listing
              else if ( name.isDirectory() ) {
                     String directory[] = name.list();
                 outputArea.append( "\n\nDirectory contents:\n");
                 for ( int i = 0; i < directory.length; i++ )
                    outputArea.append( directory[ i ] + "\n" );
              } // fim do else if da linha 184 - testa se ? um diret?rio
           } // fim do if da linha 62 - testa se o arquivo existe
           // not file or directory, output error message
           else {
              JOptionPane.showMessageDialog( this,
                 actionEvent.getActionCommand() + " Does Not Exist",
                 "ERROR", JOptionPane.ERROR_MESSAGE );
        }  // fim do m?todo actionPerformed
        // m?todo que chama o conversor
        public String chamaConversor(String arquivoPdf){
            String arquivoTxt = new String(arquivoPdf);
            arquivoTxt = arquivoPdf.replace(".pdf", ".txt");
            try {
                conversor.pdfToText(arquivoPdf,arquivoTxt);
            catch (Exception ex) {
                ex.printStackTrace();
            return (arquivoTxt);
        // executa a aplica??o
        public static void main( String args[] )
           ConstrutorDeTemplate2 application = new ConstrutorDeTemplate2();
           application.setDefaultCloseOperation (
              JFrame.EXIT_ON_CLOSE );
        } // fim do m?todo main
    }  // fim da classe ExtratorDeSubstantivos2
      * PdfToText.java
      * Created on 11 de Agosto de 2007, 10:57
      * To change this template, choose Tools | Template Manager
      * and open the template in the editor.
    //package br.unifacs.dis2007.template2;
      * @author www
    package br.unifacs.dis2007.template2;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.net.MalformedURLException;
    import java.net.URL ;
    import org.pdfbox.pdmodel.PDDocument;
    import org.pdfbox.pdmodel.encryption.AccessPermission;
    import org.pdfbox.pdmodel.encryption.StandardDecryptionMaterial;
    import org.pdfbox.util.PDFText2HTML;
    import org.pdfbox.pdmodel.font.PDFont.* ;
    import org.pdfbox.util.PDFTextStripper;
    import org.pdfbox.util.*;
    import org.pdfbox.pdmodel.*;
    public class PdfToText
        public void pdfToText( String pdfFile, String textFile) throws Exception
                Writer output = null;
                PDDocument document = null;
                try
                    try
                        //basically try to load it from a url first and if the URL
                        //is not recognized then try to load it from the file system.
                        URL url = new URL( pdfFile );
                        document = PDDocument.load( url );
                        String fileName = url.getFile();
                        if( textFile == null && fileName.length () >4 )
                            File outputFile =
                                new File( fileName.substring( 0,fileName.length() -4 ) + ".txt" );
                            textFile = outputFile.getName();
                    catch( MalformedURLException e )
                        document = PDDocument.load( pdfFile );
                        if( textFile == null && pdfFile.length() >4 )
                            textFile = pdfFile.substring( 0,pdfFile.length() -4 ) + ".txt";
                       //use default encoding
                      output = new OutputStreamWriter( new FileOutputStream( textFile ) );
                    PDFTextStripper stripper = null;
                    stripper = new PDFTextStripper();
                    stripper.writeText( document, output );
                finally
                    if( output != null )
                        output.close();
                    if( document != null )
                        document.close();
                }//finally
            }//end funcao
     

    All of these libraries are in "Compile-time
    Libraries" option in Project Properties. Should I add
    they to "Run-time Libraries" option?Yes

  • Problems with String.split(regex)

    Hi! I'm reading from a text file. I do it like this: i read lines in a loop, then I split each line into words, and in a for loop I process ale words. Heres the code:
    BufferedReader reader = new BufferedReader(new FileReader(file));
    String line;
    while ((line = reader.readLine()) != null) {
        String[] tokens = line.split(delimiters);
        for (String key : tokens) {
    doSthToToken();
    reader.close();The problem is that if it reads an empty line, such as where is only an "\n", the tokens table has the length == 1, and it processes a string == "". I think the problem is that my regex delimiters is wrong:
    String delimiters = "\\p{Space}|\\p{Punct}";
    Could anybody tell me what to do?

    Ok, so what do you suggest?I suggest you don't worry about it.
    Or if you are worried then you need to test the two different solutions and do some timings yourself.
    And how do you know the regex lib is so slow and badly written?First of all slowness is all relative. If something takes 1 millisecond vs 4 milliseconds is the user going to notice? Of course not which is why you are wasting your time trying to optimize an equals() method.
    A general rule is that any code that is written to be extremely flexible will also be slower than any code that is written for a specific function. Regex are used for complex pattern matching. StringTokenizer was written specifically to split a string based on given delimiters. I must admit I haven't tested both in your exact scenario, but I have tested it in other simple scenarios which is where I got my number.
    By the way I was able to write my own "SimpleTokenizer" which was about 30% faster than the StringTokenizer because I was able to make some assumptions. For example I only allowed a single delimiter to be specified vs multiple delimiter handled by the StringTokenizer. Therefore my code could be very specific and efficient. Now think about the code for a complex Regex and how general it must be.

  • A web developer problem while running a web application

    Hi all,
    I'm novice to J2EE.
    I've encountered a problem while accessing the deployed module in weblogic 8.1 server.
    I'm sure that the webapplication module is deployed as i saw my module in administration console & also the status said that it is deployed.
    when i access my web application by specifying the proper server and port no and context root it is showing
    either 505 - resource not found error(http://localhost:7001/Suresh-2/Suresh) or 404 - not found error.( http://localhost:7001/Suresh-2/Suresh)
    Now let me elaborate what i've done till now.
    My webapplication folder structure is : C:\bea\user_projects\domains\mydomain\applications\Suresh\WEB-INF\classes\Sai\ServExamp.class
    My servlet is ServExamp.java
    I created a folder called "Suresh". In that folder created another folder called "WEB-INF". In WEB-INF created a folder called "Classes".
    Since my servlet is in package "Sai", the .class file reside in \Suresh\WEB-INF\Classes\Sai\ServExamp.class
    The source code is :
    package Sai;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class ServExamp extends HttpServlet
    public void doPost(HttpServletRequest req,HttpServletResponse res)throws IOException
    PrintWriter out=res.getWriter();
    java.util.Date today=new java.util.Date();
    out.println("<html>"+"<body>"+
    "<h1 align=center>HF\'s Chapter1 Servlet </h1>"
    +"<br>"+today+"</body>"+"</html>");
    Now i'm almost done creating a web application. Next, I constructed a simple web.xml descriptor that gives a web friendly name for my servlet, and points to the servlet. I constructed web.xml descriptor file in the WEB-INF folder (C:\bea\user_projects\domains\mydomain\applications\Suresh\WEB-INF\).
    The web.xml file source is :
    <!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
    <display-name>Hello World Web Application</display-name>
    <description>Test Servlet</description>
    <servlet>
    <servlet-name>ServExamp</servlet-name>
    <servlet-class>Sai.ServExamp</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ServExamp</servlet-name>
    <url-pattern>/Suresh</url-pattern>
    </servlet-mapping>
    </web-app>
    Now I have told Weblogic that the URI /Suresh corresponds to my servlet "Sai.ServExamp".
    My Web Application is ready to be deployed at this point. I logged onto Weblogic's admin console,
    1) clicked on deployments, then navigated to "Web Application Modules" .
    2) Clicked "Deploy new Web Application Module"
    3) Navigated to the location of your web application folder (Suresh). There was a radio button next to it indicating that I can select that folder as a valid web application.
    4) I Clicked that radio button and clicked "Target Module".
    5) It informed that my web application "Suresh" will be deployed to myServer.It asked a name for my web application deployment. By default it was "Suresh"
    I clicked Deploy.
    6) After deployment, my web application "Suresh" appeared in the "Web Application Modules" tree on the left.
    I Clicked on "Suresh"( my web application) then clicked the testing tab, then clicked the link shown there(http://localhost:7001/Suresh-2).
    It was not showing my servlet (showed a 403 error)
    Error - 403
    This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.
    I think so it came b'coz I don't have an index.html or index.jsp page.
    7)Instead,I added my servlet on to the URL it provided.
    http://localhost:7001/Suresh-2/Suresh
    It is showing these error code: Http: 505 resource not allowed
    The page cannot be displayed
    The page you are looking for cannot be displayed because the address is incorrect.
    Please try the following:
    If you typed the page address in the Address bar, check that it is entered correctly.
    Open the localhost:7001 home page and then look for links to the information you want.
    Click Search to look for information on the Internet.
    when i just type : http://localhost:7001/ -> Error 404 not found error
    it's showing
    Error 404--Not Found
    From RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1:
    10.4.5 404 Not Found
    The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent.
    If the server does not wish to make this information available to the client, the status code 403 (Forbidden) can be used instead. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address.
    I want to run my web application & any help would be appreciated.
    Thanks in advance.
    with regards,
    S.SayeeNarayanan.
    Note: I even deployed my war file, which i got by execution of (jar cv0f webapp.war . ) command from the root directory of my web application i.e. Suresh
    Then executed my webapplication it is showing
    error-505 resource not allowed.
    --------------------------------------------------------------------------------------------

    try a fully qualified path to the pem file

  • Problem with my program looking for the settings file in the wrong folder

    I have been writing a simple FTP file uploader, what I want to do is be able to select the files I want to upload in windows explorer and then right click and click the menu item and it launches the program and passes the files paths that I have selected to it.
    So I use this in the windows registry "C:\Program Files\Java\jre1.6.0_03\bin\java.exe -jar D:\BenFTP\BenFTP.jar %1"
    It launches fine and has no problem finding the files I want to upload. The problem is that it tries to look for the settings file in the same folder that the file I am try to upload is in. Which it's not suppose to do since the settings file is in the same folder that the .jar is in.
    Edited by: ColNewman on Feb 5, 2008 6:55 PM

    So, you're looking for your settings file in your current working directory. There's no way to set the CWD in your registry entry (is there?) so that isn't a practical thing to do. Presumably you're using a File object or a FileReader or something? Can't do that.
    One alternative is to look for the settings file in the classpath. You can get a URL to a file in the classpath like this:URL settings = this.getClass().getResource("/settings.xml");Or you can get an InputStream to read the file by using the getResourceAsStream method. You would have to make sure that your executable jar file contained a Class-Path entry that specified the right directory, because the directory the jar is contained in isn't automatically in an executable jar's classpath.
    Another alternative is to ask the user where the settings file is supposed to be, and put an entry in the Preferences (java.util.prefs) to remember that location.

  • Arraylist.add() problem

    Hi,
    I'm trying to read a CSV text file into an arraylist.
    I can read the text file fine, its just when it gets to the actual arraylist.add() part it just .. .. doesn't work. It can print the values from the CSV file no problem. I'm sure my syntax is fine, everything compiles. I've read it and double checked it and checked it again.
    It just doesn't work .. I don't know why.
    The arraylist I am trying to read into is
    ArrayList<Customer> customers = new ArrayList<Customer>();Within other parts of the program I can read in dummy data, eg
    customers.add(new Customer(01, "Jims Mowing", "16 Long Grass Street", "Thorndale", "123-4567", "[email protected]"));
    but suffice to say, yes, it is kaput.
       * READING THE CUSTOMER TEXT FILE INTO THE ARRAY LIST
      private void custFileToArray ()
        RectangleTUI results = new RectangleTUI(); // create results object
        try   
          BufferedReader inputStream = new BufferedReader(new FileReader(PATHNAME + CUSTFILE));
          System.out.println("Contents of file: " + CUSTFILE); // print heading
          String line = inputStream.readLine(); // read first line
          while (line !=null) // test for end of file (EOF)
            results.loadCustFile(line);       
            line = inputStream.readLine(); // read next line
          // close file
          inputStream.close();
        // catch any file open errors
        catch(FileNotFoundException e)
          System.out.println("Error opening file: " + CUSTFILE);
          System.exit(0);
        catch(NoSuchElementException e)
          System.out.println("ATTENTION: One or more " + CUSTFILE + " records are missing data");
        // catch any file reading errors
        catch(IOException e)
          System.out.println("Error reading from file: " + CUSTFILE);
          System.exit(0);
        System.out.println("File Reading Complete");  
      private void loadCustFile(String textLine)
        String delimiters = ","; // set tokenizer delimiter
        StringTokenizer RecordFields = new StringTokenizer(textLine,delimiters);  
        int cidNum = Integer.parseInt(RecordFields.nextToken()); // Customer ID
        System.out.println(cidNum + " Hello I am a stupid piece of code. I don't like to work properly");
        String cName = RecordFields.nextToken();   // Name
        String cAdd = RecordFields.nextToken();   // Street Address
        String cBurb = RecordFields.nextToken();   // Suburb
        String cPhone = RecordFields.nextToken();   // Phone
        String cEmail = RecordFields.nextToken();   // Email
        customers.add(new Customer(cidNum, cName, cAdd, cBurb, cPhone, cEmail));
      }

    Cowzor wrote:
    Hi,
    Cheers for the replies & the printStackTrace tip.
    The thing is it's not actually throwing up any errors or crashing. It's acting as if everything is AOK - but since it then says there's nothig in the arraylist there must be a problem ... somewhere.
    Sorry if I've mis-understood what you were saying
    Here's the dummy data I'm using just incase it's at all relevant
    200701,Jims Mowing,16 Long Grass Street,Thorndale,123-4567,[email protected]
    200702,Chevy Racers,2 Raceway Drive,Boganville,123-4567,[email protected]
    200703,Renta Dent,82 Airport Oaks Road,Airport Oaks,123-4567,[email protected]
    200704,Discount Taxis,8 Poor Place,Otara,123-4567,[email protected]
    u split contains of CSV file on basis of , (comma) and read it

  • Problem with ArrayList

    Hello,
    I am having a problem with a program I am trying to write. The idea of the program is to:
    A) read a list of movies list from a text file
    B) create an object for each movie using the information from the text file
    C) place the objects into an arrayList
    My problem is that when I check my arrayList it seems to only contain multiple copies of the first movie read from the text file. Here is my code
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.FileOutputStream;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    public class MovieReader
         PrintWriter outputStream = null;
         public void readFile()
              try
                      BufferedReader in = new BufferedReader(new FileReader("movie.txt"));
                      String str;
                      while ((str = in.readLine()) != null)
                           process(str);
                      in.close();
              catch (IOException e)
                  e.printStackTrace();
         ArrayList <ValidMovie> movieList = new ArrayList<ValidMovie>();
         private void process(String line)
              String[] array = line.split("\t");
              int i = 0;
              for ( i = 0; i < array.length; i++)
                   String tempTitle = array[0];
                   String tempYear = array [1];
                   String tempRating = array [2];
                   String tempFormat = array [3];
                   ValidMovie uuj = new ValidMovie(tempTitle, tempYear, tempRating, tempFormat);
                   movieList.add(uuj);
              System.out.println("item at index 1 is:   " + movieList.get(1));
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
         private void writeFile(String [] arrayL)
              String [] arrayWrite = arrayL;
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     
    //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
         public static void main(String[] args)
              MovieReader mv = new MovieReader();
              mv.readFile();
    //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
    }This is the code that creates an object for each movie:
    import java.io.Serializable;
    public class ValidMovie implements Serializable
         private String title;
         private String year;
         private String rating;
         private String format;
         public ValidMovie()
         public ValidMovie(String tTitle, String tYear, String tRating, String tFormat)
              title = tTitle;
              year = tYear;
              rating = tRating;
              format = tFormat;
         //Getters for title, year, rating and format
         public String getTitle ()
              return title;
         public String getYear ()
              return year;
         public String getRating ()
              return rating;
         public String getFormat ()
              return format;
         public String toString ()
              return title + "\t" + year + "\t" + rating + "\t" + format;
    }The following is what I have in the movie.txt file:
    Bamboozled     2000     2     DVD
    What Lies Beneath     2000     1.5     DVD
    Beneath the Planet of the Apes     1970     1     DVD
    You Can Count On Me     2000     3.5     Theater
    And finally this is the result when I run the code:
    item at index 1 is: Bamboozled     2000     2     DVD
    item at index 1 is: Bamboozled     2000     2     DVD
    item at index 1 is: Bamboozled     2000     2     DVD
    item at index 1 is: Bamboozled     2000     2     DVD
    I am sure that it is something simple that I am overlooking but I cannot figure it out. When I change the index in the code:
    System.out.println("item at index 1 is:   " + movieList.get(1));to 0 or 2 or 3 then result is the same, it will just show the first movie in the text file. Any help would be greatly appreciated. Thanks

    Thanks for the reply, it helped but I am now getting 4 of each of the movies after adding you suggestion. This is much better now I just need to figure out why the loop is causing the extra copies. Thanks again :)
    Item 0: Bamboozled     2000     2     DVD
    Item 1: Bamboozled     2000     2     DVD
    Item 2: Bamboozled     2000     2     DVD
    Item 3: Bamboozled     2000     2     DVD
    Item 4: What Lies Beneath     2000     1.5     DVD
    Item 5: What Lies Beneath     2000     1.5     DVD
    Item 6: What Lies Beneath     2000     1.5     DVD
    Item 7: What Lies Beneath     2000     1.5     DVD
    Item 8: Beneath the Planet of the Apes     1970     1     DVD
    Item 9: Beneath the Planet of the Apes     1970     1     DVD
    Item 10: Beneath the Planet of the Apes     1970     1     DVD
    Item 11: Beneath the Planet of the Apes     1970     1     DVD
    Item 12: You Can Count On Me     2000     3.5     Theater
    Item 13: You Can Count On Me     2000     3.5     Theater
    Item 14: You Can Count On Me     2000     3.5     Theater
    Item 15: You Can Count On Me     2000     3.5     Theater

  • Problem with Background image and JFrame

    Hi there!
    I've the following problem:
    I created a JFrame with an integrated JPanel. In this JFrame I display a background image. Therefore I've used my own contentPane:
    public class MContentPane extends JComponent{
    private Image backgroundImage = null;
    public MContentPane() {
    super();
    * Returns the background image
    * @return Background image
    public Image getBackgroundImage() {
    return backgroundImage;
    * Sets the background image
    * @param backgroundImage Background image
    public void setBackgroundImage(Image backgroundImage) {
    this.backgroundImage = backgroundImage;
    * Overrides the painting to display a background image
    protected void paintComponent(Graphics g) {
    if (isOpaque()) {
    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());
    if (backgroundImage != null) {
    g.drawImage(backgroundImage,0,0,this);
    super.paintComponent(g);
    Now the background image displays correct. But as soon as I click on some combobox that is placed within the integrated JPanel I see fractals of the opened combobox on the background. When I minimize
    the Frame they disappear. Sometimes though I get also some fractals when resizing the JFrame.
    It seems there is some problem with the redrawing of the background e.g. it doesn't get redrawn as often as it should be!?
    Could anyone give me some hint, on how to achieve a clear background after clicking some combobox?
    Thx in advance

    I still prefer using a border to draw a background image:
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.border.*;
    public class CentredBackgroundBorder implements Border {
        private final BufferedImage image;
        public CentredBackgroundBorder(BufferedImage image) {
            this.image = image;
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            int x0 = x + (width-image.getWidth())/2;
            int y0 = y + (height-image.getHeight())/2;
            g. drawImage(image, x0, y0, null);
        public Insets getBorderInsets(Component c) {
            return new Insets(0,0,0,0);
        public boolean isBorderOpaque() {
            return true;
    }And here is a demo where I load the background image asynchronously, so that I can launch the GUI before the image is done loading. Warning: you may find the image disturbing...
    import java.awt.*;
    import java.io.*;
    import java.net.URL;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class BackgroundBorderExample {
        public static void main(String[] args) throws IOException {
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame f = new JFrame("BackgroundBorderExample");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JTextArea area = new JTextArea(24,80);
            area.setForeground(Color.WHITE);
            area.setOpaque(false);
            area.read(new FileReader(new File("BackgroundBorderExample.java")), null);
            final JScrollPane sp = new JScrollPane(area);
            sp.setBackground(Color.BLACK);
            sp.getViewport().setOpaque(false);
            f.getContentPane().add(sp);
            f.setSize(600,400);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            String url = "http://today.java.net/jag/bio/JagHeadshot.jpg";
            final Border bkgrnd = new CentredBackgroundBorder(ImageIO.read(new URL(url)));
            Runnable r = new Runnable() {
                public void run() {
                    sp.setViewportBorder(bkgrnd);
                    sp.repaint();
            SwingUtilities.invokeLater(r);
    }

  • I'm at my wits end!!! Can't find the problem!!!

    okay, I've got the code written for a vending machine program. i have a text file that loads in field variables to a product class, a money class that handles the basic functions of money handling methods, and a vending machine applet. the files compile fine, but they don't execute. i get an error: nosuchmethod error: main, you know the kind. i don't have a main because i'm trying to run it as an applet, but it won't run when i use appletviewer, it just does't do anything! This is going to be a tough one. But i swear up and down that i will literally find some way to pay the person who can find what the heck is wrong with the code...so, here it is, and i know it's long, but this is the final project in my java class at college, and i can't find where i'm going wrong.
    the vendingmachine:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.NumberFormat;
    import java.util.StringTokenizer;
    import utilities.CashIn;
    import utilities.Product;
    public class VendingMachine extends Applet implements ActionListener {
    private Font boldSerif16 = new Font("Serif",Font.BOLD,16);
    private Font boldSerif24 = new Font("Serif",Font.BOLD,24);
    private Font boldItalicSerif24 = new Font("Serif",Font.BOLD+Font.ITALIC,24);
    private Font boldItalicSerif13 = new Font("Serif",Font.BOLD+Font.ITALIC,13);
    private Font boldItalicSerif40 = new Font("Serif",Font.BOLD+Font.ITALIC,40);
    // Mode flag.
    private int mode = 0;
    // Panels for the buttons
    private Panel mainPanel = new Panel();
    private Panel cashPanel = new Panel();
    private Panel selPanel = new Panel();
    private Panel maintPanel = new Panel();
    // Product selection panel buttons
    private Button selBtn[] = new Button[6];
    // Cash customer puts in machine panel buttons
    private Button viewC = new Button("View The Products");
    private Button quit = new Button("Quit");
    private Button bNickle = new Button("Nickel");
    private Button bDime = new Button("Dime");
    private Button bQuarter = new Button("Quarter");
    private Button b$Paper = new Button("$1 Paper");
    private Button b$Coin = new Button("$1 Coin");
    private Label lCredit = new Label(" Credit:");
    private Label lMsg = new Label("");
    private Button bChange = new Button("Change Return");
    private Button purchase = new Button("Purchase");
    private Button maintenance = new Button("Maintenance");
    private Product productForSale [];
    private CashIn changeOH;
    private int $collected = 0;
    private double total$In = 0.00;
    private NumberFormat nf;
    private Image pic;
    private Image picAnim;
    private int prodSel = 999;
    private String line;
    private String f[] = new String[8];
    private int tokenCount;
    private int int3, int4, int5, int6, int7;
    private double dbl4;
    private StringTokenizer strings;
    private int dispense = 99;
    public void init()
    {  setLayout(new BorderLayout());
    productForSale = new Product[6];
    try
    {  BufferedReader inPut = new BufferedReader(new FileReader("Startup.txt"));
    while ((line=inPut.readLine()) != null)
    {  strings = new StringTokenizer(line,",");
    tokenCount = strings.countTokens();
    // Loop thru and retrieve each data element.
    for (int i=0; i<tokenCount; i++)
    f[i] = strings.nextToken();
    // Load the money.
    if (f[0].compareTo("M") == 0)
    {  int3 = Integer.parseInt(f[3]);
    int4 = Integer.parseInt(f[4]);
    int5 = Integer.parseInt(f[5]);
    int6 = Integer.parseInt(f[6]);
    int7 = Integer.parseInt(f[7]);
    changeOH = new CashIn(f[1],f[2],int3,int4,int5,int6,int7);
    // Load the products.
    if (f[0].compareTo("P") == 0)
    {  int3 = Integer.parseInt(f[3]);
    dbl4 = (new Double(f[4])).doubleValue();
    int5 = Integer.parseInt(f[5]);
    int6 = Integer.parseInt(f[6]);
    int7 = Integer.parseInt(f[7]);
    productForSale[int3] = new Product(f[1],f[2],dbl4,int5,int6,int7);
    inPut.close();
    catch(IOException e)
    {  e.printStackTrace();
    setBackground(Color.blue);
    setForeground(new Color(120,0,120));
    setFont(boldSerif16);
    cashPanel.setLayout(new GridLayout(10,1));
    cashPanel.add(viewC);
    cashPanel.add(quit);
    cashPanel.add(bNickle);
    cashPanel.add(bDime);
    cashPanel.add(bQuarter);
    cashPanel.add(b$Paper);
    cashPanel.add(b$Coin);
    cashPanel.add(lCredit);
    cashPanel.add(lMsg);
    cashPanel.add(bChange);
    add(cashPanel,"East");
    selPanel.setLayout(new GridLayout(1,6));
    for (int i=0; i<6; i++)
    {  selBtn[i] = new Button(productForSale.getName());
    selPanel.add(selBtn[i]);
    add(selPanel,"South");
    setBackground(Color.black);
    viewC.addActionListener(this);
    quit.addActionListener(this);
    bNickle.addActionListener(this);
    bDime.addActionListener(this);
    bQuarter.addActionListener(this);
    b$Paper.addActionListener(this);
    b$Coin.addActionListener(this);
    bChange.addActionListener(this);
    nf = NumberFormat.getCurrencyInstance();
    for (int i=0; i<6; i++)
    selBtn[i].addActionListener(this);
    } // =======>> END OF INIT METHOD
    // ** PAINT METHOD **
    public void paint(Graphics g)
    {  int xVal = 35;
    int yVal = 85;
    int xValAnim = 0;
    int yValAnim = 0;
    int c = 0;
    // Paint the product pictures on the vending machine.
    g.setColor(Color.cyan);
    g.setFont(boldItalicSerif24);
    g.drawString(changeOH.getLogo1(),115,40);
    g.setFont(boldItalicSerif13);
    g.drawString(changeOH.getLogo2(),200,60);
    for (int z=0; z<2; z++)
    {  xVal = 35;
    yVal = 85;
    c = 0;
    g.setColor(Color.black);
    g.fillRect(xVal,yVal,500,350);
    g.setColor(Color.yellow);
    for (int i=0; i<2; i++)
    {  for (int j=0; j<3; j++)
    {  g.setFont(boldSerif16);
    g.drawString(nf.format(productForSale[c].getPrice()),xVal+45,yVal-5);
    pic = getImage(getCodeBase(),productForSale[c].getPic());
    g.drawImage(pic,xVal,yVal,null);
    // If product is dispensed get ready to animate.
    if (c == dispense)
    {  xValAnim = xVal;
    yValAnim = yVal;
    picAnim = pic;
    xVal = xVal + 170;
    c++;
    yVal = yVal + 160;
    xVal = 35;
    // If product is dispensed, animate it.
    if (dispense < 99)
    {  for (int y=0; y<40; y++)
    {  g.setColor(Color.black);
    g.fillRect(xValAnim,yValAnim-9,125,125);
    g.setColor(Color.yellow);
    g.drawImage(picAnim,xValAnim,yValAnim,null);
    yValAnim = yValAnim + 10;
    pause(3);
    dispense = 99;
    if (mode == 0)
    {  pic = getImage(getCodeBase(),"OutStock.gif");
    g.drawImage(pic,300,300,null);
    g.setColor(Color.black);
    g.fillRect(1,1,500,300);
    g.setColor(Color.pink);
    g.setFont(boldItalicSerif40);
    g.drawString(changeOH.getLogo1(),10,150);
    g.setFont(boldItalicSerif24);
    g.drawString(changeOH.getLogo2(),160,250);
    mode++;
    } // =======>> END OF PAINT METHOD
    // ** ACTIONPERFORMED METHOD **
    public void actionPerformed(ActionEvent event)
    {  Object source = event.getSource();
    lMsg.setText(" Enter up to $1.00");
    // Customer puts money in the vending machine.
    // Customer paid a nickle
    if (source == bNickle && $collected < 96)
    {  changeOH.nickleIn();
    $collected = $collected + 5;
    // Customer paid a dime
    if (source == bDime && $collected < 91)
    {  changeOH.dimeIn();
    $collected = $collected + 10;
    // Customer paid a quarter
    if (source == bQuarter && $collected < 76)
    {  changeOH.quarterIn();
    $collected = $collected + 25;
    // Customer paid a paper dollar
    if (source == b$Paper && $collected == 0)
    {  changeOH.dollarPaperIn();
    $collected = $collected + 100;
    // Customer paid a coin dollar
    if (source == b$Coin && $collected == 0)
    {  changeOH.dollarCoinIn();
    $collected = $collected + 100;
    // Customer makes their product selection.
    for (int i=0; i<6; i++)
    {  if (source == selBtn[i])
    // Do nothing if customer selects item that isn't on-hand.
    if (productForSale[i].getOnHand() == 0)
    repaint();
    // We have product on-hand.
    else
    {  prodSel = i;
    // Tell customer to add more money if they don't have
    // enough in the machine to handle the purchase.
    if ($collected < (int) (productForSale[i].getPrice() * 100))
    { lMsg.setText("    Insert Money");
    // Customer has enough money in machine to cover purchase.
    else
    {  // Take cost of item from customer's money
    dbl4 = productForSale[i].getPrice() * 100;
    int4 = changeOH.giveChange($collected - (int)dbl4,0);
    // Tell customer to put exact amount in the machine
    // because there isn't enough change to handle purchase.
    if (int4 == 9)
    {  lMsg.setText("Exact Amount Only!");
    // **** Here the purchase was made and committed. ****
    else
    {  total$In = productForSale[i].getPrice() * 100;
    $collected = $collected - (int) total$In;
    productForSale[i].sellProduct();
    dispense = i;
    repaint();
    // If the last product item was sold, set picture to OutStock.gif.
    if (productForSale[i].getOnHand() <= 0)
    productForSale[i].setOutOfStock();
    if ((source == bChange || source == quit) && $collected > 0)
    {  $collected = changeOH.giveChange($collected,1);
    // Here we save the machine info file when customer asks
    // for their change back or quits the machine.
    // Customer has selected to Quit the vending machine program.
    // Quit the program.
    if (source == quit)
    System.exit(0);
    // These commands set up variables to show how much money
    // the customer has in the machine.
    total$In = $collected;
    total$In = total$In / 100;
    lCredit.setText(" Credit: " + nf.format(total$In));
    repaint();
    } // =======>> END OF ACTIONPERFORMED METHOD
    // ** PAUSE METHOD **
    public void pause(int i)
    {  for(long l = System.currentTimeMillis() + (long) i; System.currentTimeMillis() < l;);
    This is the product class:
    package utilities;
    import java.io.*;
    import java.util.StringTokenizer;
    public class Product {
    private String name;
    private String image;
    private String picUsed;
    private double price;
    private int onHand;
    private int sold;
    private int maint;
    public Product(String n, String i, double p, int o, int s, int m)
    {  name    = n;
    image = i;
    picUsed = i;
    price = p;
    onHand = o;
    sold = s;
    maint = m;
    // Reset picture used when product is out of stock.
    public void setOutOfStock()
    {  picUsed  = "OutStock.gif";
    // Get product information
    public String getName()
    {  return name;
    public String getImage()
    {  return image;
    public String getPic()
    {  return picUsed;
    public double getPrice()
    {  return price;
    public int getOnHand()
    {  return onHand;
    public int getQtySold()
    {  return sold;
    public int getMaintDate()
    {  return maint;
    // Sell one of the product.
    public void sellProduct()
    {  onHand--;
    sold++;
    // Set the product values.
    public void setName(String n)
    {  name = n;
    public void setImage(String i)
    {  image   = i;
    picUsed = i;
    public void setPrice(double p)
    {  price = p;
    public void setOnHand(int o)
    {  onHand = o;
    public void setQtySold(int s)
    {  sold = s;
    public void setMaintDate(int m)
    {  maint = m; }
    The money class:
    package utilities;
    import java.math.*;
    public class CashIn {
    private String logo1;
    private String logo2;
    private int numProd;
    private int nickles;
    private int dimes;
    private int quarters;
    private int dollarsP;
    private int dollarsC;
    private int money;
    private double moneyVal;
    private int amtToChange = 0;
    private int hNickle;
    private int hDime;
    private int hQuarter;
    private int hpDollar;
    private int hcDollar;
    public CashIn(String l1, String l2, int p, int q, int d, int n, int dP)
    {  logo1    = l1;
    logo2 = l2;
    numProd = p;
    quarters = q;
    dimes = d;
    nickles = n;
    dollarsP = dP;
    dollarsC = 0;
    money = (n * 5) + (d * 10) + (q * 25) + (dP * 100);
    // Get total of money in machine.
    public double getCashIn()
    {  moneyVal = money;
    moneyVal = moneyVal / 100;
    return moneyVal;
    // Get machine record information.
    public String getLogo1()
    {  return logo1;
    public String getLogo2()
    {  return logo2;
    public int getNumProd()
    {  return numProd;
    public int getNickles()
    {  return nickles;
    public int getDimes()
    {  return dimes;
    public int getQuarters()
    {  return quarters;
    public int getDollarPaper()
    {  return dollarsP;
    public int getDollarCoins()
    {  return dollarsC;
    // Money comes into the machine
    public void nickleIn()
    {  nickles++;
    money = money + 05;
    public void dimeIn()
    {  dimes++;
    money = money + 10;
    public void quarterIn()
    {  quarters++;
    money = money + 25;
    public void dollarPaperIn()
    {  dollarsP++;
    money = money + 100;
    public void dollarCoinIn()
    {  dollarsC++;
    money = money + 100;
    // Give the customer their change.
    public int giveChange(int custMoney, int mode)
    {  hNickle   = nickles;
    hDime = dimes;
    hQuarter = quarters;
    hpDollar = dollarsP;
    hcDollar = dollarsC;
    amtToChange = custMoney / 100;
    for (int i=0; i<amtToChange; i++)
    {  // Give change in dollar coin if possible
    if (hcDollar > 0)
    {  hcDollar--;
    custMoney = custMoney - 100;
    // or else give change in paper dollar
    else
    {  if (hpDollar > 0)
    {  hpDollar--;
    custMoney = custMoney - 100;
    amtToChange = custMoney / 25;
    for (int i=0; i<amtToChange; i++)
    {  if (hQuarter > 0)
    {  hQuarter--;
    custMoney = custMoney - 25;
    amtToChange = custMoney / 10;
    for (int i=0; i<amtToChange; i++)
    {  if (hDime > 0)
    {  hDime--;
    custMoney = custMoney - 10;
    amtToChange = custMoney / 5;
    if (amtToChange > hNickle)
    {  mode = 9;
    for (int i=0; i<amtToChange; i++)
    {  hNickle--;
    custMoney = custMoney - 5;
    if (mode == 1)
    {  nickles   = hNickle;
    dimes = hDime;
    quarters = hQuarter;
    dollarsP = hpDollar;
    dollarsC = hcDollar;
    money = money - custMoney;
    if (mode == 9) custMoney = 9;
    return custMoney;
    the startup text:
    p,Fritos,Images/FritoLay.gif,
    m,$.50,
    p,Dr. Pepper,Images/Dr.Pepper.gif,
    m,$.60,
    p,Pepsi,Images/Pepsi.gif,
    m,$.60,
    p,Coke,Images/CocaCola.gif,
    m,$.60,
    p,Seven-Up,Images/7-Up.gif,
    m,$.60,
    p,Sprite,Images/Sprite.gif,
    m,$.60,
    c,10,20,40,

    S/he's only offering six Dukes here:
    http://forum.java.sun.com/thread.jsp?forum=54&thread=469450&start=0&range=15#2169975
    This problem has been done before. Break this down into something simpler. You don't need an applet. Just do it on the command line. You don't need a database. Just create a flat file if you need some persistent data. Do the simple thing first, then build out from there.
    Click on the special tokens link up above and learn how to use [ code][ code] tags.
    Your code is a big, unreadable mess. You've got pare this down into something sensible. If you can't understand it, it's unreasonable to expect someone on this forum to wade through all of that. - MOD

  • Problem with read() and EOF

    I'm inputting a file that has a total of 18 entries delimited by commas Ex. ( 4, 5, 200, 780, 1, 0, 0, 12, 6, 0, 129, 24, 21, 44, 133, 62, 158, 7). My problem is that on the very last entry I can't get it to stop because it's looking for a comma. I tried all sorts of things like checking for if current.read() == -1 and so on but nothing seems to trigger it. If I change the while loop to go for one more time through it gives me 7followed by infinite "?". No errors are thrown so I can't even pinpoint anything that way. All I need to do is be able to read the last set of characters after the last comma and then make it stop and this program will work the way it's supposed to. Any suggestions??
                            try {
                        BufferedReader input = new BufferedReader( new FileReader( fileField.getText() ) );
                        char current = ' ';
                        int i = 0;
                        String temp;
                        while ( i < 17 ){
                             temp = new String( "" );               
                             current = (char)input.read();
                             while( current != ',' ){
                                  if( current == ' ' ){
                                  else {
                                       System.out.print( current );
                                       temp += String.valueOf( current );
                                  current = (char)input.read();
                             System.out.println( "temp = " + temp );
                             switch( i ) {
                                  case 0:     verField.setText( temp ); break;
                                  case 1: hlenField.setText( temp ); break;
                                  case 2:     servField.setText( temp ); break;
                                  case 3: totalField.setText( temp ); break;
                                  case 4: fragIDField.setText( temp ); break;
                                  case 5: flagField.setText( temp ); break;
                                  case 6: fragOffField.setText( temp ); break;
                                  case 7: TTLField.setText( temp ); break;
                                  case 8: protocolField.setText( temp ); break;
                                  case 9: headerField.setText( temp ); break;
                                  case 10: sIP1Field.setText( temp ); break;
                                  case 11: sIP2Field.setText( temp ); break;
                                  case 12: sIP3Field.setText( temp ); break;
                                  case 13: sIP4Field.setText( temp ); break;
                                  case 14: dIP1Field.setText( temp ); break;
                                  case 15: dIP2Field.setText( temp ); break;
                                  case 16: dIP3Field.setText( temp ); break;
                                  case 17: dIP4Field.setText( temp ); break;          
                             i++;     
                   catch( FileNotFoundException f ){
                   catch( IOException f ){
                   }/

    The following should work.
        public interface Settable {
            public void setText(String s);
        private static final Settable[] FIELDS = {verField, hlenField, servField, totalField, fragIDField, flagField, fragOffField, TTLField, protocolField, headerField, sIP1Field, sIP2Field, sIP3Field, sIP4Field, dIP1Field, dIP2Field, dIP3Field, dIP4Field};
        public void code(String fileName) {
            try {
                LineNumberReader input = new LineNumberReader(new FileReader(fileName));
                // read line and split by a comma with any number of spaces on either side.
                String[] vars = input.readLine().split(" *, *");
                for(int i = 0; i < vars.length && i < FIELDS.length;i++)
                    FIELDS.setText(vars[i]);
    } catch (IOException f) {
    f.printStackTrace();

Maybe you are looking for

  • Windows live messenger disconnection on nokia 6022...

    Hi up until recently I could log into windows live messenger on my mobile, now when I log in I get a error 201 and a message say that "you were disconnected from windows live messenger - server initiated disconnect" then asks  if I want to connect ag

  • Primary contact and contact field in activity

    Hi all, I am trying to create few contacts under an account and set one contact as primary contact. Then i am trying to craete an activity for that account.In that Activity there are two fields "Contact" and "Primary Contact".But when I try to pick u

  • Stock Avaliability Before Billing

    I want the system to automatically check stock quantity when Billing so that i won't over bill the customer or sell what i dont have. eg i have 20 cartons of vimto (Finished Product) in stock and unknowing to me i have raised sales order for 21 carto

  • ASP pages

    Hi, I'd like to know how I can work with Oracle in classical ASP pages considering security problems like SQL injection. If possible I'd like code example. Thank you, Teo

  • Unwanted blue border in Acrobat

    I have imported a Flash movie into an InDesign document. I then export the document as an interactive PDF. The movie plays fine in Acrobat, but after playing a thin blue border appears around the movie area. Anyone know why or more importantly, how t