Compare file using string tokenizer

hi there..
i have a file creation file_20061208.txt
and how am i suppose to tokenize it so i can juz retrieve 20061208??

ok this is my code so how do i go abt tokenising it?     
files = directory.listFiles();
               File lastModifiedFile = null;
               for (int i = 0; i < files.length; i++)
                    if(files.isFile())
                         if(lastModifiedFile == null)
                         lastModifiedFile = files[i];
                         if(lastModifiedFile != null)
                              if(lastModifiedFile.lastModified() < files[i].lastModified())
                                   lastModifiedFile = files[i];

Similar Messages

  • How to retrieve IndividualStrings from a txt file using String Tokenizer.

    hello can any one help me to retrieve the individual strings from a txt file using string tokenizer or some thing like that.
    the data in my txt file looks like this way.
    Data1;
    abc; cder; efu; frg;
    abc1; cder2; efu3; frg4;
    Data2
    sdfabc; sdfcder; hvhefu; fgfrg;
    uhfhabc; gffjcder; yugefu; hhfufrg;
    Data3
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    i need to read the data as an individual strings and i need to pass those values to diffarent labels,the dat in Data3 i have to read those values and add to an table datamodel as 6 columns and rows depends on the data.
    i try to retrieve data using buffered reader and inputstream reader,but only the way i am retrieving data as an big string of entire line ,i tried with stringtokenizer but some how i was failed to retrive the data in a way i want,any help would be appreciated.
    Regards,

    Hmmm... looks like the file format isn't even very consistent... why the semicolon after Data1 but not after Data2 or Data3??
    Your algorithm is reading character-by-character, and most of the time it's easier to let a StringTokenizer or StreamTokenizer do the work of lexical analysis and let you focus on the parsing.
    I am also going to assume your format is very rigid. E.g. section Data1 will ALWAYS come before section Data2, which will come before section Data3, etc... and you might even make the assumption there can never be a Data4, 5, 6, etc... (this is why its nice to have some exact specification, like a grammar, so you know exactly what is and is not allowed.) I will also assume that the section names will always be the same, namely "DataX" where X is a decimal digit.
    I tend to like to use StreamTokenizer for this sort of thing, but the additional power and flexibility it gives comes at the price of a steeper learning curve (and it's a little buggy too). So I will ignore this class and focus on StringTokenizer.
    I would suggest something like this general framework:
    //make a BufferedReader up here...
    do
      String line = myBufferedReader.readLine();
      if (line!=null && line.trim().length()>0)
        line = line.trim();
        //do some processing on the line
    while (line!=null);So what processing to do inside the if statement?
    Well, you can recognize the DataX lines easily enough - just do something like a line.startsWith("Data") and check that the last char is a digit... you can even ignore the digit if you know the sections come in a certain order (simplifying assumptions can simplify the code).
    Once you figure out which section you're in, you can parse the succeeding lines appropriately. You might instantiate a StringTokenizer, i.e. StringTokenizer strtok = new StringTokenizer(line, ";, "); and then read out the tokens into some Collection, based on the section #. E.g.
    strtok = new StringTokenizer(line, ";, ");
    if (sectionNo==0)
      //read the tokens into the Labels1 collection
    else if (sectionNo==1)
      //read the tokens into the Labels2 collection
    else //sectionNo must be 2
      //create a new line in your table model and populate it with the token values...
    }I don't think the delimiters are necessary if you are using end-of-line's as delimiters (which is implicit in the fact that you are reading the text out line-by-line). So the original file format you listed looks fine (except you might want to get rid of that rogue semicolon).
    Good luck.

  • How to read a file using string tokenizer   ?

    He everybody
    I am bit new to java !
    i have a text file call Student.txt which contain a StudentName + thier marks
    like this way
    Shane 60
    Will 73
    Lorenzo 12
    What i need to do is i need to use stringtokenizer class to populate an array of Student name and marks and display the array ?
    i need to store Studentname as a String and Marks as integer ?
    how do i do this task ?
    help me to solve my problem !
    regards
    suis

    Hallo,
    I am giving a sample code and just look at that one, and think about your requirement.
    File file = new File(" employee.txt");
    FileReader freader = new FileReader(file);
    BufferReader breader = new BufferReader(freader);
    String inLine = null;
    while ((inLine = inputStream.readLine()) != null) {
    st = new StringTokenizer(inLine, DELIM);
    String studentname[] =String[10];
    for(int i=0; i<studentname.length;i++)
    studentname[i] = st.nextToken();
    int marks[] = new int[10];
    for ( int i=0;i<marks.length;i++)
    marks[i] = st.nextToken();
    If you want print out these value, you can...
    Best Regards
    Maruthi

  • Using String Tokenizer on connection string

    I have a database connnection string like so:
    jdbc:oracle:thin:@<url>:<port number>:<database name>
    I'm planning to use String Tokenizer to extract the database name. Is this possible. Where can I start?

    I have a database connnection string like so:
    jdbc:oracle:thin:@<url>:<port number>:<database
    name>
    I'm planning to use String Tokenizer to extract the
    database name. Is this possible. Where can I start?You can tokenize on ":". Then put eack token on a list. Yourdatabase name will be last element of the list. Take a look at on StrnngTokenizer API.

  • How can i delete a UserName  from a text file using Strings or io.

    hi i m trainee
    i have been assigned to make java program which deletes a UserName and
    his Passwor from a Text File
    i m unable to do it using the code below
    plz help
    do reply
      import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java .applet.*;
    import java.io.*;
    class Del extends JFrame  implements ActionListener
         String s2;
         JTextField CWDMUserDText = new JTextField();
         JButton CWDMSecDelButton = new JButton("DELETE");
         JLabel CWDMUserLabel = new JLabel("USER NAME");
         JPasswordField CWDMPassDText = new JPasswordField();
         JLabel CWDMPassLabel = new JLabel("PASSWORD");
         //String user,pass;
         /* CONSTRUCTOR*/
              Del()
                   Container contentPane=getContentPane();
                   contentPane.setLayout(null);
                  setLocation(400,200);
                   contentPane.add(CWDMUserDText);
                   contentPane.add(CWDMSecDelButton);
                   contentPane.add(CWDMUserLabel);
                   contentPane.add(CWDMPassDText);
                   contentPane.add(CWDMPassLabel);
                  CWDMUserLabel.setBounds(20,70,100,25);
                  CWDMPassLabel.setBounds(20,100,100,25);
                   CWDMUserDText.setBounds(150,70,100,25);
                   CWDMPassDText.setBounds(150,100,100,25);
                   CWDMSecDelButton.setBounds(80,135,100,25);
                   CWDMUserDText.addActionListener(this);
                   CWDMPassDText.addActionListener(this);
                   CWDMSecDelButton.addActionListener(this);
                   contentPane.setBackground(Color.CYAN);
                   setVisible(true);
                   setDefaultCloseOperation(EXIT_ON_CLOSE);
         public void actionPerformed(ActionEvent ae)
                  if(ae.getSource()==CWDMSecDelButton)
         //             user = CWDMUserDText.getText();
         //          pass = CWDMPassDText.getText();
         //          showarr();
                   s2 = CWDMUserDText.getText();
                   CWDMUserDText.setText("");
                   CWDMPassDText.setText("");
                   DelUser(s2);
              public static void main(String args[])
                   Del myframe1= new Del();
                   myframe1.setSize(300,200);
                   myframe1.setVisible(true);
              public void DelUser(String s)
                   //int a;
                   try
                        FileReader fr = new FileReader("file.txt");
                        BufferedReader br = new BufferedReader(fr);
                       String s1;
                       int a;
                       int len = s.length();
                       System.out.println(len);
                       //s2 = CWDMUserDText.getText();
                        while ((s1=br.readLine()) !=null)
                             if((a=s1.indexOf(s))>0 && (a=s1.indexOf(s))!=0)
                                  System.out.println(a);
                        fr.close();
                   catch(FileNotFoundException e)
                        System.out.println("exception occured");
                   catch(IOException e)
                        System.out.println("io");
         }

    Some tips:
    1) If you are adding or deleting stuff from a text file you need to write a new, modified file and then, optionally, do something like:
    rename the old file to whatever.bak or the like.
    rename the new file to the old.
    2) Don't depend on System.out so much on a GUI application. For example if you get an exception use javax.swing.JOptionPane to display an alert (and show the message from the exception). You can write the stack trace to System.out if you want.
    3) Don't muck about with calculating bounds for screen objects, let a layout manager sort it out. I like BoxLayoutManager for most things like this.
    4) For bonus points do your IO in a separate Thread. Generally you don't want anything happening in an actionPerformed method which significantly delays it's return. The method should launch a new Thread to do the job, and disable the button until the Thread finishes.

  • Using String Tokenizer in constructors

    Hi there,
    I am supposed to create a constructor name called Abbreviation (String abbrName, String fullName).
    and Im given a list of abbreviation and their full name as followed in a text file: eg:
    US - United States
    UK - United Kingdom
    How do I initialize the objects using the Abbreviation class?
    I have done some codings, please do take a look:
    public Abbreviation(String abbrName, String fullName)
                   this.abbrName = abbrName;
                   StringTokenizer strToken = new StringTokenizer(fullName, "- ");
                   //how do I count the number of abbreviation and stored them in a array ?
    Thanks..

    You need to create a new instance of your Abreviation class for each line you read from the file, so you can't read the file in the constructor. The constructor gets called for each instance of the class you create.
    I wouldn't recommend StringTokenizer here, unless it's specified in your project. There are various ways you could try. I suggest you read up on String.split(), and regular expressions. (you might use the java.util.regexp.Pattern class).
    Also read up on ArrayList.

  • Dos command to compare files using adobe acrobat pro 9.

    Hi,
    I am using Adobe Acrobat Pro 9, through its utility i am comparing two pdfs using its GUI. Now i want to compare two pdfs through Dos prompt using Adobe Acrobat Pro 9. Is there any Dos command to compare two pdfs using Adobe Acrobat Pro 9.
    Regards 

    I don't think so.

  • Trying to use string tokenizer but not working as expected

    Hello friends,
    In the following code, I am trying to acheive an output like this:
    Manju Nambiar
    Mini Nambiar
    -variable mc stands for the maximum number characters allowed in a line.
    -variable wb stands for wordbreak allowed i.e if set to false, a word should be printed as it is without splitting even if the maxchar limit is crossed, but then the next word should come on the next line.
    String input = "Manju Nambiar Mini Nambiar";
    String token;
    String wb = "f";
    String newlineop = System.getProperty("line.separator");
    int mc = 10;
    if(wb.equalsIgnoreCase("f"))
    StringTokenizer splitip = new StringTokenizer(input," ");
    while(splitip.hasMoreTokens())
    token = splitip.nextToken();
    System.out.println("length is:"+newlineop.length());
    if((newlineop.length())<mc)
    newlineop = newlineop.concat(token+" ");
    else
    newlineop = newlineop.concat(newline+token);
    System.out.println(newlineop);
    The output I am getting is:
    Manju Nambiar
    Mini
    Nambiar
    I know it is because of the length of the newlineop variable that I am checking in the loop - but I am not able to see how to circumvent this??? :-(
    Please Help,
    Thanks,
    Manju

            String input = "Manju Nambiar Mini Nambiar";
            String token;
            boolean wb = false; // as Nasch pointed out, use boolean here
            String newlineop = System.getProperty("line.separator");
            int tokenLength = 0; // variable to check length of line
            int mc = 10;
            if (!wb)
                StringTokenizer splitip = new StringTokenizer(input, " ");
                while (splitip.hasMoreTokens())
                    token = splitip.nextToken();               
                    if (tokenLength < mc)
                        tokenLength += token.length();
                        newlineop = newlineop.concat(token + " ");
                    else
                        tokenLength = token.length(); //new line, reset length
                        newlineop = newlineop.concat("\n" + token + " ");
            System.out.println(newlineop);
        ram.

  • Parsing and String tokenizer

    I am trying to use String Tokenizer to extract fields from a file then do a calculation on some of the fields.
    My problem is when I try to parse the strings that need the calculations I get error codes as shown at the end of post. I don't see why the parsing shouldn't work.( error codes are class expected and incompatable types)
    // ParsingTextFile.java: Process text file using StringTokenizer
    import java.io.*;
    import java.util.StringTokenizer;
    public class ParsingTextFile1 {
      /** Main method */
      public static void main(String[] args) {
       // Declare  buffered file reader and writer streams
       BufferedReader brs = null;
       BufferedWriter bws = null;
       //declare tokenizer
       StringTokenizer tokenizer;
       // Declare a print stream
       PrintWriter out = null;
        // Five input file fields:total string, student name, midterm1,
        // midterm2, and final exam score
        String line=null;
        String sname = null;
       String mid1= null;
        String mid2 = null;
        String finalSc = null;
      /  double midterm1 = 0;
        double midterm2 = 0;
        double finalScore = 0;
        // Computed total score
        double total = 0;
        try {
          // Create file input and output streams 
          brs = new BufferedReader(new FileReader("in.dat"));
          bws = new BufferedWriter(new FileWriter("out.dat"));
         while((line= brs.readLine())!=null){
         tokenizer =new StringTokenizer(line);
          sname = tokenizer.nextToken();
          mid1 = tokenizer.nextToken();
          mid2 = tokenizer.nextToken();
          finalSc= tokenizer.nextToken();
          midterm1 = double.parseDouble(mid1)//this code not working
          midterm2 = double.parseDouble(mid2);)//this code not working
          finalScore = double.parseDouble(finalScore);//this code not working
          out = new PrintWriter(bws);
          total = midterm1*0.3 + midterm2*0.3 + finalScore*0.4;
          out.println(sname + " " + total);
        catch (FileNotFoundException ex) {
          System.out.println("File not found: in.dat");
        catch (IOException ex) {
          System.out.println(ex.getMessage());
        finally {
          try {
            if (brs != null) brs.close();
            if (bws != null) bws.close();
          catch (IOException ex) {
            System.out.println(ex);
    }[\code]
    errorsC:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:43: class expected
        midterm1 = double.parseDouble(mid1);
                          ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:44: class expected
        midterm2 = double.parseDouble(mid2);
                          ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:45: class expected
        finalScore = double.parseDouble(finalScore);
                            ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:43: incompatible types
    found   : java.lang.Class
    required: double
        midterm1 = double.parseDouble(mid1);
                         ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:44: incompatible types
    found   : java.lang.Class
    required: double
        midterm2 = double.parseDouble(mid2);
                         ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:45: incompatible types
    found   : java.lang.Class
    required: double
        finalScore = double.parseDouble(finalScore);
                           ^
    6 errors
    Process completed.

    while(line.hasMoreTokens())
    sname = tokenizer.nextToken();  
       mid1 = tokenizer.nextToken();   
      mid2 = tokenizer.nextToken();  
       finalSc= tokenizer.nextToken(); 
        midterm1 = double.parseDouble(mid1)//this code not working
         midterm2 = double.parseDouble(mid2);)//this code not working  
       finalScore = double.parseDouble(finalScore);//this code not working
    }if it doesn't work then you need to add delimiter Or the token that you are trying to convert into is not valid.

  • Regarding string tokenizer

    Hello all,
    Can anybody help me to get the file name which is specified in the path like C:/programs/folder/example.txt" or "C:/programs/folder/test.txt" or "C:/programs/example/verify.txt" . The path name will change dynamically in my program.
    What I want to do is to get the filename from the path using string tokenizer.
    Thanks in advance.

    I think I do. Why don't you try that code snippet out
    and see that when you invoke File.getName it returns
    you the file name with the path part stripped out.
    Isn't that what you said you wanted?Even if that ability did not exist (but clearly a programmer should always use it if it is available) then it would be simply to substring the full path starting at last index of the current platform's file separator, and ending at the end of the path string.

  • How to compare and edit Resource bundle file using java programe

    Hi All
    I have two resource bundle with key, value and some comments. I need to write a java code to compare both of the values of the keys and if the values are different then i want to replace the second value with the first value.
    Its a programe which will udpate the second file with the first file values.
    I tried using Properties class but it didnt worked because when i am saving the file using store method it removes all the comments and the order of text also got disturbed.
    How I need to do this any help appriciated.
    Please elt me know if someone needs more info.
    Thanks in advance.

    Let's assume the ini file is a mapping type storage (key=value) so lets use Properties object. (works with java 1.4 & up)
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Properties;
    public class Test {
         private static Properties props;
         public static void main(String[] args) throws IOException {
              File file = new File("test.ini");//This is out ini file
              props = new Properties();//Create the properties object
              read(file);//Read the ini file
              //Once we've populated the Properties object. set/add a property using the setProperty() method.
              props.setProperty("testing", "value");
              write(file);//Write to ini file
         public static void read(File file) throws IOException {
              FileInputStream fis = new FileInputStream(file);//Create a FileInputStream
              props.load(fis);//load the ini to the Properties file
              fis.close();//close
         public static void write(File file) throws IOException {
              FileOutputStream fos = new FileOutputStream(file);//Create a FileOutputStream
              props.store(fos, "");//write the Properties object values to our ini file
              fos.close();//close
    }

  • Do i need to use a string tokenizer here?

    I am doing a program that reads a text file and write it to another new file. Before, writing out the required text lines to a new file, the program should be able to extract certain words from the text file that had been read and the user can able to put some semicolons after certain word character. Do i need to use substring or string tokenizer in order to extarct the words and add some chracters to it??? i dunt understand how to do it. Can anyone help me out here?..thanks.

    sure, uncle. here i give u the input and the sample out put it should be. Another thing, is that my data length for certain characters are not same , so how would i determine the appropriate length to put the semicolon....the example input :
    470615-03-5039058004TA SECURITIES HOLDINGS BERHAD 000891226AB KARIM BIN MAT HUSSIN LOT 2761 DEPAN ESSO TG MAS JALAN PENGKALAN CHEPA15400 KOTA BHARU 15400DMYSMYSBI 09-7735699 8516 000000080000000100 812974
    this is stored in a file n the program will read it
    then, it shud put semicolon at certain parts n write it out back. i try to use the insert code but it only works for string buffer as im using buffer reader here.
    the output should be.
    470615-03-5039 ; 004; SECURITIES HOLDINGS BERHAD ;00891226AB ; KARIM BIN MAT HUSSIN; LOT 2761 DEPAN ESSO TG MAS ; JALAN PENGKALAN CHEPA;15400 KOTA BHARU ; 15400;D;MY;SMYSBI ;09-7735699 8516 ;000000080000000100; 2812974 ...the semicolons shud be put here...but there are different numbers for this part ( 470615-03-5039 )....for example...(978T)...so, how am i goin to determine the correct part to put the semicolon????..plz help me...thanks

  • How to read from a xml file(in String format) using a java program

    hi friends
    i have a string , which is xml format. i want read the values and display it.can any one suggest how to read a xml file of string format using a javaprogram
    thanks

            final DocumentBuilder db =  DocumentBuilderFactory.newInstance().newDocumentBuilder();      
            final InputStream documentStream = new ByteArrayInputStream(documentXMLSourceString.getBytes("utf-8"));
            final Document document = db.parse(documentStream);

  • Compare two pdf files using adobe acrobat through command line

    Does anyone know how to compare two pdf files using adobe acrobat through command line. I want to do this via command line because we want to compare hundreds of file every day through some automated windows tasks.
    If command line option is not available in acrobat, then is it feasible to make use of acrobat javascript API to do this task?
    Any kind of help will be greatly.

    Command-line: Not possible.
    JavaScript: Possible, but very limited. Basically the only thing you can do is simulate clicking the Compare Documents button. The rest has to be done manually.
    However, it *might* be possible to automate this process a bit more using a plugin. Ask over at the Acrobat SDK forum for more information...

  • How do i search for a string in a txt file using java??

    How do i search for a string in a txt file using java??
    could you please help thanks
    J

    Regular expressinos work just fine, especially when
    searching for patterns. But they seem to be impying
    it's a specific group of characters they're looking
    for, and indexOf() is much faster than a regex.If he's reading from a file, the I/O time will likely swamp any performance hit that regex introduces. I think contains() (or indexOf() if he's not on 5.0 yet) is preferable to regex just because it's simpler. (And in the case of contains(), the name makes for a very clear, direct mapping between your intent and the code that realizes it.)

Maybe you are looking for