Reading files in java

Hi people!
Help needed one again. Basically i have a buffered reader which i use tto read a file. After i read a line i send it to a method to break down into sentences by full stop, which is done using regualr expression Pattern[,]. However when the text is written as follows:
Berline wall falls down
by Peter.
It sent the first line and then the second line. What i need it to do is keep reading until it reaches a full stop. Ive posted my code below. Any help would be much appreciated.
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class BreakSentence
Vector sentence = new Vector(500);
public BreakSentence(String fileName)
     try
          BufferedReader input = new BufferedReader(new FileReader(fileName));
          String line = input.readLine();
          while(line!=null)
               makeSentence(line); //Call method to split text file into sentences based on full stop.
               line = input.readLine();
          input.close();
     catch(FileNotFoundException e)
          System.out.println(e);
     catch(IOException e2)
          System.out.println(e2);
private void makeSentence(String a)
     Pattern p = Pattern.compile("[.]");
          // Split input with the pattern
          String[] sentences = p.split(a);
          for( int i=0; i < sentences.length; i++ )
               if(sentences[i] == null || sentences.length() == 1)
               else
               //String noPunc = removePunctuation(sentences[i]);               //remove puncuations
               //System.out.println( "With punctuation: " + sentences[i] );
               //System.out.println( "Without punctuation: " + noPunc );
               //sentence.add( sentences[i].trim() );
               //sentence.add(noPunc.trim());
               sentence.add(sentences[i]);
public void printInformation()
     for(int i =0; i<sentence.size(); i++)
          System.out.println("Position"+ i+ " " +sentence.get(i)  );
public static void main(String[]args)
BreakSentence x = new BreakSentence( "output2.txt" );
x.printInformation();

Please use code tags.
Check out [url http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html]Pattern.[url http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html#compile(java.lang.String,%20int)] compile(String regex, int flags) and [url http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html#MULTILINE]MULTILINE

Similar Messages

  • How to open/read file using Java in Unix?

    Hi Friends,
    Can you please help me out how to open/read file using java in unix os? I have create one text file in "/home/test.txt" in unix environment. How to open the same file & read using java code?
    - Hiren Modi

    http://java.sun.com/docs/books/tutorial/essential/io/index.html

  • Reading files from Java embedding.

    Dear All,
    My BPEL process has a Java embedding node, and it invokes a Java class, in which an xsl file is being read for transformation.
    I deploy the xsl files directory together with BPEL package (the jar). In the package, I put the file dir at the root level, which means the jar structure looks like the following:
    /BPEL-INF
    /META-INF
    /xsd
    /xsl
    *.wsdl
    *.bpel
    bpel.xml
    The java class is package in /BPEL-INF dir, it's supposed to read files from /xsl dir.
    My question is, how should I put the file path?
    I tried "/xsl/***.xsl" and "../xsl/***.xsl", neither works. Although "/xsl/***.xsl" worked when testing in JDeveloper, but FileNotFound after deployment.
    Thanks,
    Haibo

    I solved this issue by putting the files dir in /BPEL-INF/classes/. and use ClassLoader to read in those files.

  • 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);

  • Read file gives java.lang.Nullpointer exception

    I am reading to read a ".txt" file created by "python code" and stored in my directory.
    If i comment the python code and store the file ("statusfile.txt') in the directory, the code is able to read the file. but when i uncomment and run the python code to generate the file ..it gives java.lang.NullPointerException.
    the two functions for reading the file and running the python code are separate but in the same class and are also called in one JSP. Does anyone have any suggestions.
    Someone did suggest me to use getResourceAsStream.. but i do not understand where to use it .. in the class (where i am doing the readfile function or where in the runpython function which basically generates the file) I did tried using it in JSP and also in the class.. but nothing seems to work. Also as i saw the examples.. getResourceAsStream is used for uploading properties or config files. I just want to simplying read the simpel text file which is already stored in the directory and return a boolean to JSP if reading file was a success.
    in short the algo is
    ON JSP:
    1) call class function to run python code
    2) call class function to read the generated in step 1.
    CLASS
    1) function runpython()
    // store generated files in the specified directory
    2) function readFile()
    //read file from specified directory
    //return boolean
    Any suggestions
    Thanx

    The problem is where is "your directory"?
    Creating a file by new File("myFile.txt") just puts it in the current working directory.
    Sometimes this is something like the bin directory.
    Most web applications use ServletContext.getRealPath("/")
    This turns a website relative reference into a file reference on the local machine.
    So you can say getRealPath("/index.html") and it will return the file (for example) C:\tomcat\webapps\root\index.html
    On to suggestions:
    Null pointer exception?
    Where is it coming from? Catch the exception and print a stack trace, to see if you can determine which line of code is causing it - which variable is null. Is it the actual file, or something you use to create the file?

  • Reading file from Java Web App?

    My application has a custom configuration file that I want to read at runtime.
    What directory should I put the file in and how should my code locate the file at runtime?
    Obviously, I don't want to hardcode paths.
    Is there an easy way to find the file at runtime if it's in my classpath root?
    (sorry for the repetition, I posted a vartion of this question at the end of another thread.)

    Just read your post in the other thread ... another why of doing this could be to set your own environment variable and then use it within your app.
    ie. in a DOS window (or better still, use the Environment Variables option within the Properties of My Computer).
    c:\>set myAppCfgFile = c:\myapp\myconfig.inithen in Java.
    String pathAndFilename = System.getenv("myAppCfgFile"); // note, environment variables are not case sensitive (or shouldn't be).

  • Read file in servlet

    In the servlet file, I create a new object which is class A(which is not subclass of servlet).
    And class A have a method to read a txt file.
    However, no matter I put the file in what directory such as tomcat/webapps/home/WEB-INF/classes, or just in home, when the servlet file and new the object of class A, and then call the read file method. java.lang.NullPointerException occurs.
    How should I do?
    thx~~

    use the absolute path in the constructor
    of the reader you use to read the file.
    then it should work.

  • Error reading zip file in Java 6

    We have a bespoke installer program that fails, intermittently, in Java 6 on Windows. After installing some files, it then fails with a stack trace like this:
    java.util.zip.ZipException: error reading zip file
         at java.util.zip.ZipFile.read(Native Method)
         at java.util.zip.ZipFile.access$1200(ZipFile.java:29)
         at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:447)
         at java.util.zip.ZipFile$1.fill(ZipFile.java:230)
         at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:141)
         at java.io.FilterInputStream.read(FilterInputStream.java:90)
         at com.XXXX.trent.installer.Installer.writeStreamToFile(Unknown Source)
         at com.XXXX.trent.installer.Installer.installFile(Unknown Source)
         at com.XXXX.trent.installer.PatchFileInstaller.installFile(Unknown Source)
         at com.XXXX.trent.installer.PatchFileInstaller.installFiles(Unknown Source)
         at com.XXXX.trent.installer.UpgradeInstaller$TpfAction.run(Unknown Source)
         at com.XXXX.trent.installer.UpgradeInstaller.runActions(Unknown Source)
         at com.XXXX.trent.installer.UpgradeInstaller.install(Unknown Source)
         at com.XXXX.trent.installer.TrentInstall$SoftwareInstallStage.install(Unknown Source)
         at com.XXXX.trent.installer.TrentInstall$UpgradeInstallWorker.install(Unknown Source)
         at com.XXXX.trent.installer.PatchInstall$InstallWorker.construct(Unknown Source)
         at com.XXXX.trent.utils.SwingWorker$2.run(Unknown Source)
         at java.lang.Thread.run(Thread.java:619)The same code works in Java 5 on the same environments that it now fails in Java 6 (1.6.0_16).
    Any ideas?
    Thanks.

    gimbal2 wrote:
    it is not weird, it is a bug in the application. Don't let the upgrade from Java 5 to Java 6 make you believe otherwise.It's a singularly bad exception message though. I would have thought that something from java.util might be a bit more explicit about what the problem is.
    Winston

  • How to read Excel file in java

    Respected sir/madam
    I want to read the values from Excel file in Java program. How can I do that. When I searched over the net I came to know that you can treat Excel file as a Database and write the code as u write for making DB connections .
    I did that but i am getting the following error ..can anybody please help..
    This is the code what i have written
    import java.io.*;
    import java.sql.*;
    public class ReadExcelFile {
    Connection c;
    Statement stmnt;
    public void checkABA_Number()
    try
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    c = DriverManager.getConnection("jdbc:odbc:ExcelTest","",""); // ExcelTest is the DSN name
    stmnt = c.createStatement();
    ResultSet rs = stmnt.executeQuery("select * from abadata"); // abadata is my Excel file name
    while(rs.next())
    System.out.println(rs.getString(1)+" "+rs.getString(2));
    }catch(Exception e)
    System.out.println(""+e.toString());
    finally
    try
    stmnt.close();
    c.close();
    catch( Exception e )
    System.err.println( e );
    public static void main(String[] args)
    new ReadExcelFile().checkABA_Number();
    My Excel file starts from the first row and first column and also the first row contains the names of the column.
    It give me the following error..
    java.sql.SQLException: [Microsoft][ODBC Excel Driver] The Microsoft Jet database engine could not find the object 'abadata'. Make sure the object exists and that you spell its name and the path name correctly.
    How can I deal with this.?I have properly selected the worksheet while giving the DSN . Is there any versionig problem with Excel or some drivers are in appropriate..and yes i chose Microsoft Excel Driver (.xsl) from ODBC .
    I created System DSN.
    Can anybody please help me with this ? I will be very gratefull for replies
    Thanks in advance

    here is the code to read excel file
    public void readexel(String filename)
    Connection c = null;
    Statement stmnt = null;
    try
    Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
    c = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=" + filename);
    stmnt = c.createStatement();
    String query = "Select * from [Sheet1$]" ;
    ResultSet rs = stmnt.executeQuery( query );
    while( rs.next() )
    System.out.println( rs.getString(1) );
    catch( Exception e )
    System.err.println( e );
    }

  • How to read pdf files using java.io package classes

    Dear All,
    I have a certain requirement that i should read and write PDF files at runtime. With normal java file IO reading is not working. Can any one suggest me how to proceed probably with sample code block
    Thanks in advance.

    hi I also have the pbm. to read pdf file using JAVA
    can any body help meWhy is it so difficult to read the thread you posted in? They say: java.io is pointless, use iText. So why don't you?
    or also I want to read a binary encoded data into
    ascii,
    can anybody give me a hint how to do it.Depends on what you mean with "binary encoding". ASCII's binary encoding, too, basically.

  • 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 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

  • Read multiple files and write data on a single  file in java

    Hello,
    I am facing difficulty that I want to read multiple files in java and write their data to a single file. Means Write data in one file from multiple files in java
    Please help me out.
    Naveed.

    algorithm should be something like:
    File uniqueFile = new File();
    for (File f : manyFilesToRead)
       while (readingF)
           write(dataFromF, intoUniqueFile);

  • 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);

  • Reading an RTF file in Java

    Hi,
    Can someone tell me how can we read the data from an .rtf files like we do with text files in Java.
    I have seen solutions using Swing rtfeditor etc.. But I just need to read the data, I do not want to open rtf page.
    Any help would be appreciated.
    KK

    If you are not to "read" but to obtain bytes then you can modify this:
    //try{
      InputStream stream = new FileInputStream("cc.rtf");//file name is arbitrary
                                                                             //or BufferedInputStream can be used
       int n=0;
    while((n=stream.read())!=-1){
                System.out.print(Integer.toString(n));
                System.out.print(" ");
        System.out.println();
       if(stream!=null) stream.close();
    //   catch(IOException ioe){
    //       throw ioe;
    //  }

Maybe you are looking for

  • Cisco ASA -VPN Ping Question

    Hey guys, I have a Cisco ASA 5505 8.4 I have a Remote Access VPN up and working...for the most part. When I VPN in I would like to be able to access our Mitel phone manager which is just a internal IP you put in the browser. Here is the issue when I

  • ORDER BY in view definitions

    ORDER BY was not allowed in view definitions in 7.3.4. It is allowed in 8.1.6 but I have not seen any documentation to say when or why it was introduced. There is an old rule that a select statement does not guarantee the order of rows without an ord

  • File Adapter - functionality

    Hi I am using file adapter to read 'n' number of files. I need to know which record is from which file. Basically I need to distinguish between records of different files. For example      In FILE_1 i have record like First Name  Last Name   WorkLog_

  • Photos in 1 Event disappeared--how to retrieve from Time Michine

    This is scary, I just noticed that in one of my Events all but one of the photos has vanished. There were probably 50 in that event previously. Fortunately, I do have Time Machine connected. But with iPhoto decidedly non-user friendly format, I have

  • ORA-06571: Function TEST_FUNC does not guarantee not to update database

    I have created a very simple C function in a .dll. Everything compiles OK, and I can create the lib, package, and procedure. But when I try to use it from sql*plus: SQL> select test_func(1) from dual; select test_func(1) from dual ERROR at line 1: OR