How to read blank in java

hi guys, im totally confused about how to read blank ( no character, or space ) in order to proceed my line counter program.
thanks

i'm trying to make the program read from a textfile, and trying to do like if there is a blank then assume we can go to the next line and that blank is count as 1 line.
this is my code so far.
import java.io.*;
import java.util.*;
public class Test
     public static void main(String[] args)
                              throws FileNotFoundException
          FileReader inFile = new FileReader ("test.txt");
          PrintWriter outFile = new PrintWriter("testResult.txt");
               int numLines = 0;
               int numWords = 0;
               int numChars = 0;
               String line;
               do {
                    line = inFile.nextLine();
                    if (line != " ")
                         numLines++;
                         numChars += line.length();
                         numWords += countWords(line);
               while (line != " ");
               System.out.println("The following text has: " + "\n" + numLines + " Lines" + "\n" +
               numWords + " Words " + "\n" + numChars + " Characters");
     private static long countWords(String line)
               int numWords = 0;
               int index = 0;
               boolean prevWhitespace = true;
               while (index < line.length())
                    char c = line.charAt(index++);
                    boolean currWhitespace = Character.isWhitespace(c);
                    if (prevWhitespace && !currWhitespace)
                         numWords++;
                    prevWhitespace = currWhitespace;
               return numWords;
}and sorry for offtopic here, but i also getting an error here.
C:\Documents and Settings\Test.java:18: cannot find symbol
symbol : method nextLine()
location: class java.io.FileReader
                    line = inFile.nextLine();

Similar Messages

  • How to read OVD using java

    Hi all,
    how to access OVD using Java?
    Thanks,
    Kumar.P

    Hi,
    You can just normal LDAP API codes to connect to OVD the same way you connect to other LDAP servers.
    PFB sample code for connecting to OVD.
    Properties props = new Properties();
    try {
    props.load(new FileInputStream("LdapCredentials.Properties"));
    } catch (IOException e) {
    // TODO
    ldapurl = "ldap://hostname:390";
    ldapUser = "cn=orcladmin,ou=Org12,dc=ovid,dc=com";
    userPassword = "welcome1"; //"Killtheking123456";
    userContext = "ou=Join1,dc=ovid,dc=com";
    Now, you have to get Directory Context as shown below.
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY,
    "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapurl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, username);
    env.put(Context.SECURITY_CREDENTIALS, password);
    //Initialize the Directory context
    DirContext dCtx = new InitialDirContext(env);
    Then you can perform search operations or new user creation etc., as you wish.
    Does this help?
    -Mahendra.

  • How to read files in java

    Hi
    I have a directory that has files put into it. What I want to do is open/read these files in java and then do something to it and then move the file to another folder called passed or failed.
    What I dont know is how can I read a file who's name i dont know of?
    Example I know the directory the files will go into
    c:\test\csv\
    but the file name i dont know of they could be called anything and have any extension!
    My program will loop every 10 minutes and check if there are files in the directory. If so it will process them. Once files have been processed their should be no more files left in this directory.
    Kind Regards
    Antek

    Hi
    Thanks for your answer it pointed me in the right direction. I now have small problem. If i do directory list like the code below it gives me all the files but it also gives me any directories in the folder. How can i tell it to give me files only and no folders.
    Many thanks
    import java.io.*;
    import java.util.*;
    public class SimpleDirList
         public static void main(String [] args) {
              String directoryName;
    File directory ;
    String[] files;
              directory = new File("c:\\java_code");
              if (directory.isDirectory() == false) {
                   if (directory.exists() == false) {
                        System.out.println("There is no such directory!");
                   } else {
                        System.out.println("That file is not a directory.");
              } else {
                   files = directory.list();
                   System.out.println("Files in directory \"" + directory + "\":");
                   for (int i = 0; i < files.length; i++) {
                        //do something
                        System.out.println(" " + files);

  • How to read BLOBs as "Java.io.Reader"

    Hello,
    I have a problem dealing with BLOBs in JDBC. I want to get a BLOB as a "java.io.Reader". I have written the following code:
    class Db_templates {
    public static Reader select(int tpl_id) {
    try {
    Connection connection = ... ;
    Reader retour = null;
    String strSQL = "SELECT tpl_blob FROM templates WHERE tpl_id = ?";
    PreparedStatement ps = connection.prepareStatement(strSQL);
    ps.setInt(1, tpl_id);
    ResultSet rset = ps.executeQuery();
    if (rset.next()) {
    oracle.sql.BLOB blob = (BLOB)rset.getObject(1);
    retour = blob.characterStreamValue();
    rset.close();
    ps.close();
    connection.close();
    return retour;
    } catch (SQLException e) {
    return null;
    Then I try to call this method in a JSP file (Tomcat 4.0 as JSP container) with the following lines:
    Reader i = Db_templates.select(42);
    out.println(i.ready());
    char buf[] = new char[1000];
    try {
    int retour = i.read(buf, 1, 900);
    } catch (IOException e) {
    out.println(e.toString());
    The method i.ready() returns false with no IOException thrown.
    The method i.read() fails to execute with the following errors:
    java.lang.NullPointerException
    at oracle.sql.LobPlsqlUtil.plsql_read(LobPlsqlUtil.java:911)
    at oracle.sql.LobPlsqlUtil.plsql_read(LobPlsqlUtil.java:52)
    at oracle.jdbc.dbaccess.DBAccess.lobRead(DBAccess.java:658)
    at oracle.sql.LobDBAccessImpl.getBytes(LobDBAccessImpl.java:95)
    at oracle.sql.BLOB.getBytes(BLOB.java:175)
    at oracle.jdbc.driver.OracleBlobInputStream.needBytes(OracleBlobInputStream.java:126)
    at oracle.jdbc.driver.OracleBufferedStream.read(OracleBufferedStream.java:108)
    at oracle.jdbc.driver.OracleConversionReader.needChars(OracleConversionReader.java:151)
    at oracle.jdbc.driver.OracleConversionReader.read(OracleConversionReader.java:119)
    at org.apache.jsp.essai2$jsp._jspService(essai2$jsp.java:87)
    Any ideas?
    Thanks,
    Nicolas

    Normally, Firefox has two different behaviors for the down arrow key, assuming it is not inside a form control:
    * Scroll the page
    * With caret browsing turned on, move the cursor down one line
    If you are accustomed to the down arrow key moving among search results so you can press the Enter key to load them, and you are using Google, this is due to a script in the results page intercepting those keys and changing what they normally do.
    I have only tested Windows myself, so I don't know whether this is generally available when using Google in your distribution of Linux. If it is, then the question would be: why not on your Firefox? Hmm...

  • How to read the content in one node of XML in Java? Pls help

    My dear brothers,
    I am a newbie of XML, I have a exercise which is creating a Tree View from XML file. But the trouble is I do not know how to read the content in one node of XML file. I decide to use the algorithm as following:
    1. Create a GUI form which gives the ability for user to choose a XML file (ok)
    2. Load XML and return the file (ok)
    3. Read the file from node to node to create the node in Tree View (?!)
    Please help me, and if you are enough kind, please give me an small example to easy understand. Thanks in advance.
    Hoang Yen Binh

    I hope this one helps you.
         <ABC Type="ProductBased" ProdName="One" Location="India">
              <CEO>Raj</CEO>
              <Finance>Vikram</Finance>
              <HR>Karthik</HR>
              <Technical>Satish</Technical>
         </ABC>
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Attr;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Node;
    import org.w3c.dom.DOMException;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.SAXException;
    import java.io.File;
    import java.io.IOException;
    public class XmlReading {
         Document doc;
         Element element;
         public static void main(String[] args) throws Exception{
              XmlReading xr = new XmlReading();
              xr.getXmlParser(args);
         public void getXmlParser(String[] args) {
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   if(args.length != 1) {
                        System.err.println("Argument Required");
              try {
                   DocumentBuilder builder = factory.newDocumentBuilder();
                   doc = builder.parse(new File(args[0]));
              }catch(ParserConfigurationException e1) {
              }catch(SAXException e2) {
              }catch(IOException e3) {
              getAttributes();
         public void getAttributes() {
              // Retrive the entire Document from the Dom Tree
              element = doc.getDocumentElement();
    //          System.out.println(element);
              NamedNodeMap attrs = element.getAttributes();
              // Get number of attributes in the element
         int numAttrs = attrs.getLength();
         // Process each attribute
              for (int i=0; i<numAttrs; i++) {
                   Node node = attrs.item(i);
                   // Get attribute name and value
                   String attrName = node.getNodeName();
                   String attrValue = node.getNodeValue();
                   System.out.println(attrName + ": " + attrValue);
              String s1 = element.getTagName();
              System.out.println(s1);
              // To get all the elements in a DOM Tree
              NodeList nl1 = element.getElementsByTagName("*");
              int i2 = nl1.getLength();
              System.out.println(i2);
              for(int i=0; i<i2; i++) {
                   System.out.println(nl1.item(i) + "\n");
    }

  • How to read some records from a text file into java(not all records)

    hello,
    how to read text files into java. i need only few records from the text file not all records at a time.
    If any one knows plz reply me
    my id is [email protected]

    this snipet reads a text file line by line from line 1 to 3
    try {
                  FileReader fr = new FileReader(directory);
                  BufferedReader br = new BufferedReader(fr);
                  int counter = 0;
                  while ((dbconn = br.readLine()) != null) {
                      switch(counter){
                          case 0:
                            status = dbconn;
                          break;
                          case 1:
                            userName = dbconn;
                          break;
                          case 2:
                            apword = dbconn;
                          break;
                      counter++;
                  br.close();
        }catch(IOException e){
        }

  • How to read a data from USB port using JAVA

    hi all,
    i need to know how to read a data from USB port using java. any API are available for java ?.........please give your valuable ideas !!!!!!!!!
    Advance Thanks!!

    You can do this. Please use this link
    [http://www.google.co.in/search?hl=en&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=uHu&q=java+read+data+from+usb+port&btnG=Search&meta=&aq=f&oq=]
    What research did you do of your own? Have you done some testing application and tried yourself??

  • How to read the data from Excel file and Store in XML file using java

    Hi All,
    I got a problem with Excel file.
    My problem is how to read the data from Excel file and Store in XML file using java excel api.
    For getting the data from Excel file what are all the steps i need to follow to get the correct result.
    Any body can send me the code (with java code ,Excel sheet) to this mail id : [email protected]
    Thanks & Regards,
    Sreenu,
    [email protected],
    india,

    If you want someone to do your work, please have the courtesy to provide payment.
    http://www.rentacoder.com

  • How to Read and Generate XML file from java code.

    hi guys,
    how to read the xml file (Condition :we know only DTD or Shema only).
    How to Generate the new xml file ?(using Shema )
    And one more how directly Generate the xml from DB?
    Pleas with code or any URL

    Using XMLbeans you can generate Java objects from an XSD schema (perhaps DTDs aswell)
    Then you can create an instance of the Document object and ask it to write itself.
    This will create an XML document complient to the schema.
    XMLBeans generates a "type" safe DOM where you can only ever have a structure compilent to you schema.
    matfud

  • How to read the content of ms-word file use pure java???

    how to read the content of ms-word file use pure java???

    hi,
    check this: http://jakarta.apache.org/poi/

  • How To Read RTF file in JAVA?  Using  iText?

    How To Read RTF file in JAVA?  Using  iText?.....
    import java.io.*;
    import com.lowagie.text.*;
    import com.lowagie.text.rtf.*;
    public class RTF3 {
    public static void main(String[] args) {
    // System.out.println("This example generate a RTF file name Sample.rtf");
    // Create Document object
    Document myDoc = new Document();
    try {
    // Create writer to listen document object
    // and directs RTF Stream to the file Sample.rtf
    RtfWriter2.getInstance(myDoc, new FileOutputStream("Sample.rtf"));
    // open the document object
    myDoc.open();
    // Create a paragraph
         Paragraph p = new Paragraph();
         p.add("Helloworld in Rtf file..amazing isn't");
         // Add the paragraph to document object
    myDoc.add(p);
    catch(Exception e) {
    System.out.println(e);
    //close the document
    myDoc.close();
    Exception in thread "main" java.lang.NoSuchMethodError: com.lowagie.text.Rectangle.width()F
         at com.lowagie.text.rtf.document.RtfPageSetting.rectEquals(RtfPageSetting.java:433)
         at com.lowagie.text.rtf.document.RtfPageSetting.guessFormat(RtfPageSetting.java:362)
         at com.lowagie.text.rtf.document.RtfPageSetting.setPageSize(RtfPageSetting.java:341)
         at com.lowagie.text.rtf.RtfWriter2.setPageSize(RtfWriter2.java:248)
         at com.lowagie.text.Document.open(Unknown Source)
         at view.RTF3.main(RTF3.java:23)
    CAN you HELP me?

    import com.lowagie.text.Document;
    import com.lowagie.text.rtf.parser.RtfParser;
    import java.io.FileInputStream;
    String inputFile = "sample.rtf";
    Document document = new Document();
    document.open();
    RtfParser parser = new RtfParser(null);
    parser.convertRtfDocument(new FileInputStream(inputFile), document);

  • How to read card reader (bar code reader) in simple java program ?

    hai all
    how to manipulate (read/write) card readers (or bar code reader ) in
    a java program ?
    should i import any particular package library ?
    pls give me any sample code or tutorials or tools, etc (whatever you have) .
    i am new to this card reader category
    its very urgent
    thank you .

    Nearly all card readers and barcode readers I've ever seen simply stick their input right onto stdin, so you can capture it just as if it had been typed in on a keyboard

  • How to read a text file using Java

    Guys,
    Good day!
    Please help me how to read a text file using Java and create/convert that text file into XML.
    Thanks and God Bless.
    Regards,
    I-Talk

         public void fileRead(){
                 File aFile =new File("myFile.txt");
             BufferedReader input = null;
             try {
               input = new BufferedReader( new FileReader(aFile) );
               String line = null;
               while (( line = input.readLine()) != null){
             catch (FileNotFoundException ex) {
               ex.printStackTrace();
             catch (IOException ex){
               ex.printStackTrace();
         }This code is to read a text file. But there is no such thing that will convert your text file to xml file. You have to have a defined XML format. Then you can read your data from text files and insert them inside your xml text. Or you may like to read xml tags from text files and insert your own data. The file format of .txt and .xml is far too different.
    cheers
    Mohammed Jubaer Arif.

  • How to read a text/html file in java regardless of its encoding?

    Hi All,
    How to read a text/html file in java regardless of its encoding?
    1. Is there any way to identify that a file (read using FileInputStream/or any other means with java.io package) has been saved with which type of encoding i.e. whether the file is using ANSI encoding or Unicode encoding or other?
    2. Is there any standard way to read an encoded file (i.e. files having UTF-16 format for Asian locales character support) and un-encoded file (i.e. files having ordinary ANSI format) correctly without knowing the user input?
    The problem is that while creating an instance of 'InputStreamReader' (ISR) we can pass the encoding type used (otherwise it takes the system's default encoding type), and the ISR expects the file to be in the same encoding format otherwise it reads it as some junk. But we don't know which file the user is going to pass whether it is Unicode (for Asian locales file should be in Unicode) with or ANSI coded (for non-Asian / English locales user generally uses ANSI encoding).
    Regards,
    Sam

    1. There is no reliable way of guessing the encoding of a file without that information. Thats why XML for example has very strict rules wrt. it's encoding (short form: use UTF-8 or UTF-16, if you use anything else, you'll have to specify it)
    2. you might be able to make an educated guess if the possible range of encodings is limited, but it will probably never be 100% certain
    3. The HTML file might have a header entry "<meta http-equiv..." that tells you about it's encoding. You could try to read the start of the file and see if you find that, then if you found it re-read the entire file.
    regards

  • How to Read a CAB File from JAVA?

    Hi,
    Anyone knows how to read a CAB File from java. I need to read a property file of txt file that is packaged in CAB file & then based on that, I have to do processing. Is there anyway to do it.
    I had tried using java.util.zip.ZipFile Class, but it does work for JAR, but not for CAB.
    siva.

    Perhaps there's something in the Cabinet SDK that will help:
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncabsdk/html/cabdl.asp

Maybe you are looking for