Program to read only specific words in each Line in a text file

Hi
I have a question
I need to write a program where the program must read only specific words in each line
I will give you an example...
PSAPPSRV.21201      1-42 13.35.54 238.360 Cur#1.HDEV RC=0 Dur=0.000 COM Stmt=SELECT VERSION FROM PSVERSION WHERE OBJECTTYPENAME = 'SYS'
PSAPPSRV.21201      1-43 13.35.54 0.040 Cur#2.HDEV RC=0 Dur=0.000 COM Stmt=SELECT STYLESHEETNAME FROM PSOPTIONS
These are two lines in my text file...now I need to read only the SQL statements present that is both SELECT statements.. Can you please suggest a method.......

My first reaction to the question is why would you want such thing, but may be I am unknown :)
Assuming you have the text as string, I mean
String str = "PSAPPSRV.21201 1-42 13.35.54 238.360 Cur#1.HDEV RC=0 Dur=0.000 COM Stmt=SELECT VERSION FROM PSVERSION WHERE OBJECTTYPENAME = \'SYS\'";you can obtain the sql statement using substring method like
String result = str.substring(str.indexOf("SELECT")); Again I assume there is no word SELECT preceding and the word SELECT is all caps.

Similar Messages

  • Read the first word of each line in a text file

    i need to read the first word of each line of a text file.
    i know of line.split() but not actually sure how i would go about using it
    Any help most appreciated
    Many Thanks
    Ben

    Hi thanks for the reply!
    this is what i tried... and it still doesn't get me the first word of each line!
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.io.*;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import java.util.Calendar;
    import java.util.Scanner;
    import java.util.Vector;
    import java.text.SimpleDateFormat;
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    import java.io.BufferedReader;
    public class testing {
         Vector progs=new Vector();
         Vector rand=new Vector();
         String[] tmp = new String [2];
         String str;
         String str2="ewerwer";
         String str3;
         public void programTest()
                   try
                             BufferedReader in = new BufferedReader(new FileReader("progList.log"));
                             while ((str = in.readLine()) != null)
                                  progs.add(str);
                        catch(IOException e)
                             System.out.println("cannot read file");
         //////THE ISSUES IS HERE....I WANT TO GET THE FIRST WORD FROM EACH LINE OF THE FILE!!!     
              try
                             BufferedReader in2 = new BufferedReader(new FileReader("eventLog.log"));
                             while ((str = in2.readLine()) != null)
                                  tmp = str.split(" ");
                                  System.out.println(tmp[0]);
                        catch(IOException e)
                             System.out.println("cannot read file");
    public static void main(String[] args)
                 testing B = new testing();
                 B.programTest();
               //  B.fileToVector();
                 //B.LoginWindow();
               //B.anomDetect();
    }//end class

  • Select first word in each line of a text file to do something.

    How do I select the first word in each line to do something newer from a text file in Powershell?
    Example:
     GBL                            Primary    File            
     local                          Primary    File            
     localhost                      Primary    File            
     Opstest                        Primary    File            
     TrustAnchors                   Primary    File            
    99upgrade

    Hi 99,
    here's an example on how to do it:
    $lines = Get-Content "C:\ExampleFolder\Example.txt"
    foreach ($line in $lines)
    Write-Host ($line.Split(" "))[0]
    Just replace the Write-Host line in the loop with what you actually want to do with the first word in the line.
    Cheers,
    Fred
    There's no place like 127.0.0.1

  • Java write/append to each line of a text file

    I have spent numerous hours trying to figure out what I am doing wrong. If anyone more experienced could tell me what is wrong with my code.
    I have a very simple text file with 5 lines:
    line1
    line2
    line3
    line4
    line5
    All I am trying to do is append some string to the end of each of those lines. Everytime I run my code, it erases all content but does not write/append anything to the file. Any help is greatly appreciated.
    Thanks! I am about to throw this monitor out the window!!
    package Chapter6;
    import java.io.*;
    public class fileNavigation2 {
         public static void main(String[] args) {
              File dir = new File("C:\\testing");
              System.out.println(dir.isDirectory());
              try {
                   File file = new File(dir, "Test.txt");
                   FileReader fr = new FileReader(file);
                   BufferedReader br = new BufferedReader(fr);
                   FileWriter fw = new FileWriter(file);
                   BufferedWriter bw = new BufferedWriter(fw);
                   String s = "Add1,";
                   String s2 = "Add2\n";
                   String str;
                   while((str = br.readLine()) != null) {
                   StringBuffer sb = new StringBuffer(str);
                   sb.append(s + s2);
                   String y = sb.toString();
                   System.out.println(sb);
                   System.out.println("Appending");
                   bw.write(y);
                   bw.close();
                   System.out.println("Done");
              }catch(IOException e) {}
    }

    First, thanks a lot for your feedback. The code makes a lot of sense but it does not update the content of my Test.txt file.
    I only edited the line of code that creates the new file so that it could find the location of the file.
    Scanner file = new Scanner(new File("C:\\testing",fileName));==============================
    The code now looks like:
    import java.io.*;
    import java.util.*;
    public class Main {
        static void appendTo(String fileName, String[] newLines) throws IOException {
            List<String> allLines = getLinesFrom(fileName);
            for(String line : newLines) {
                allLines.add(line);
            writeLinesTo(fileName, allLines);
        static List<String> getLinesFrom(String fileName) throws IOException {
            List<String> lines = new ArrayList<String>();
            Scanner file = new Scanner(new File("C:\\testing",fileName));
            while(file.hasNextLine()) {
                lines.add(file.nextLine());
            file.close();
            System.out.println(lines);
            return lines;
        static void writeLinesTo(String fileName, List<String> lines) throws IOException {
            BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
            for(String line : lines) {
                out.write(line);
                out.write(System.getProperty("line.separator"));
            out.close();
        public static void main(String[] args) {
            String fileName = "Test.txt";
            String[] extraLines = {
                    "a new line",
                    "and yet another new line"
            try {
                appendTo(fileName, extraLines);
                System.out.println("Done.");
            } catch (IOException e) {
                e.printStackTrace();
    }Again, thanks for the help.

  • Reading a Random Line from a Text File

    Hello,
    I have a program that reads from a text file words. I currently have a text file around 800KB of words. The problem is, if I try to load this into an arraylist so I can use it in my application, it takes wayy long to load. I was wondering if there was a way to just read a random line from the text file.
    Here is my code, and the text file that the program reads from is called 'wordFile'
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class WordColor extends JFrame{
         public WordColor(){
              super("WordColor");
              setSize(1000,500);
              setVisible(true);
              add(new WordPanel());
         public static void main(String[]r){
              JFrame f = new WordColor();
    class WordPanel extends JPanel implements KeyListener{
         private Graphics2D pane;
         private Image img;
         private char[]characterList;
         private CharacterPosition[]positions;
         private int charcounter = 0;
         private String initialWord;
         private File wordFile = new File("C:\\Documents and Settings\\My Documents\\Java\\projects\\WordColorWords.txt");
         private FontMetrics fm;
         private javax.swing.Timer timer;
         public final static int START = 20;
         public final static int delay = 10;
         public final static int BOTTOMLINE = 375;
         public final static int buffer = 15;
         public final static int distance = 4;
         public final static Color[] colors = new Color[]{Color.red,Color.blue,Color.green,Color.yellow,Color.cyan,
                                                                          Color.magenta,Color.orange,Color.pink};
         public static String[] words;
         public static int descent;
         public static int YAXIS = 75;
         public static int SIZE = 72;
         public WordPanel(){
              words = readWords();
              setLayout(new BorderLayout());
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              setFocusable(true);
              addKeyListener(this);
              timer = new javax.swing.Timer(delay,new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        YAXIS += 1;
                        drawWords();
                        if (YAXIS + descent - buffer >= BOTTOMLINE) lose();
                        if (allColorsOn()) win();
         public void paintComponent(Graphics g){
              super.paintComponent(g);
              if (img == null){
                   img = createImage(getWidth(),getHeight());
                   pane = (Graphics2D)img.getGraphics();
                   pane.setColor(Color.white);
                   pane.fillRect(0,0,getWidth(),getHeight());
                   pane.setFont(new Font("Arial",Font.BOLD,SIZE));
                   pane.setColor(Color.black);
                   drawThickLine(pane,getWidth(),5);
                   fm = g.getFontMetrics(new Font("Arial",Font.BOLD,SIZE));
                   descent = fm.getDescent();
                   distributePositions();
                   drawWords();
                   timer.start();
              g.drawImage(img,0,0,this);
         private void distributePositions(){
              int xaxis = START;
              positions = new CharacterPosition[characterList.length];
              int counter = 0;
              for (char c: characterList){
                   CharacterPosition cp = new CharacterPosition(c,xaxis, Color.black);
                   positions[counter] = cp;
                   counter++;
                   xaxis += fm.charWidth(c)+distance;
         private void drawThickLine(Graphics2D pane, int width, int thickness){
              pane.setColor(Color.black);
              for (int j = BOTTOMLINE;j<BOTTOMLINE+1+thickness;j++){
                   pane.drawLine(0,j,width,j);
         private void drawWords(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              drawThickLine(pane,getWidth(),5);
              for (CharacterPosition cp: positions){
                   int x = cp.getX();
                   char print = cp.getChar();
                   pane.setColor(cp.getColor());
                   pane.drawString(""+print,x,YAXIS);
              repaint();
         private boolean allColorsOn(){
              for (CharacterPosition cp: positions){
                   if (cp.getColor() == Color.black) return false;
              return true;
         private Color randomColor(){
              int rand = (int)(Math.random()*colors.length);
              return colors[rand];
         private void restart(){
              charcounter = 0;
              for (CharacterPosition cp: positions){
                   cp.setColor(Color.black);
         private void win(){
              timer.stop();
              newWord();
         private void newWord(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              repaint();
              drawThickLine(pane,getWidth(),5);
              YAXIS = 75;
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              distributePositions();
              charcounter = 0;
              drawWords();
              timer.start();
         private void lose(){
              timer.stop();
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              pane.setColor(Color.red);
              pane.drawString("Sorry, You Lose!",50,150);
              repaint();
              removeKeyListener(this);
              final JPanel p1 = new JPanel();
              JButton again = new JButton("Play Again?");
              p1.add(again);
              add(p1,"South");
              p1.setBackground(Color.white);
              validate();
              again.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        remove(p1);
                        addKeyListener(WordPanel.this);
                        newWord();
         private String getWord(){
              int rand = (int)(Math.random()*words.length);
              return words[rand];
         private String[] readWords(){
              ArrayList<String> arr = new ArrayList<String>();
              try{
                   BufferedReader buff = new BufferedReader(new FileReader(wordFile));
                   try{
                        String line = null;
                        while (( line = buff.readLine()) != null){
                             line = line.toUpperCase();
                             arr.add(line);
                   finally{
                        buff.close();
              catch(Exception e){e.printStackTrace();}
              Object[] objects = arr.toArray();
              String[] words = new String[objects.length];
              int count = 0;
              for (Object o: objects){
                   words[count] = (String)o;
                   count++;
              return words;
         public void keyPressed(KeyEvent evt){
              char tempchar = evt.getKeyChar();
              String character = ""+tempchar;
              if (character.equalsIgnoreCase(""+positions[charcounter].getChar())){
                   positions[charcounter].setColor(randomColor());
                   charcounter++;
              else if (evt.isShiftDown()){
                   evt.consume();
              else{
                   restart();
              drawWords();
         public void keyTyped(KeyEvent evt){}
         public void keyReleased(KeyEvent evt){}
    class CharacterPosition{
         private int xaxis;
         private char character;
         private Color color;
         public CharacterPosition(char c, int x, Color col){
              xaxis = x;
              character = c;
              color = col;
         public int getX(){
              return xaxis;
         public char getChar(){
              return character;
         public Color getColor(){
              return color;
         public void setColor(Color c){
              color = c;
    }

    I thought that maybe serializing the ArrayList might be faster than creating the ArrayList by iterating over each line in the text file. But alas, I was wrong. Here's my code anyway:
    class WordList extends ArrayList<String>{
      long updated;
    WordList readWordList(File file) throws Exception{
      WordList list = new WordList();
      BufferedReader in = new BufferedReader(new FileReader(file));
      String line = null;
      while ((line = in.readLine()) != null){
        list.add(line);
      in.close();
      list.updated = file.lastModified();
      return list;
    WordList wordList;
    File datFile = new File("words.dat");
    File txtFile = new File("input.txt");
    if (datFile.exists()){
      ObjectInputStream input = new ObjectInputStream(new FileInputStream(datFile));
      wordList = (WordList)input.readObject();
      if (wordList.updated < txtFile.lastModified()){
        //if the text file has been updated, re-read it
        wordList = readWordList(txtFile);
        ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
        output.writeObject(wordList);
        output.close();
    } else {
      //serialized list does not exist--create it
      wordList = readWordList(txtFile);
      ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
      output.writeObject(wordList);
      output.close();
    }The text file contained one random sequence of letters per line. For example:
    hwnuu
    nhpgaucah
    zfbylzt
    hwnc
    gicgwkhStats:
    Text file size: 892K
    Serialized file size: 1.1MB
    Time to read from text file: 795ms
    Time to read from serialized file: 1216ms

  • How to finds specific words in each sentence?

    import java.io.*;
    import java.text.*;
    import java.util.*;
    public class FindingWordsSpecific {
         static String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "every Tuesday"};
      public static void main( String args[] ) throws IOException {
               // the file must be called 'myfile.txt'
               String s = "myfile.txt";
               File f = new File(s);
               if (!f.exists())
                    System.out.println("\'" + s + "\' does not exit. Bye!");
                    return;
               BufferedReader inputFile = new BufferedReader(new FileReader(s));
               String line;
               int nLines = 0;
               while ((line = inputFile.readLine()) != null)
                    nLines++;
                   System.out.println(findTheIndex(line));     
               inputFile.close();
           public static String findTheIndex(String sentence){
                String result = "";
                String[] s = sentence.split("\\s");
              for (String s1: s){
                   for (String s2: days){
                        if (s1.equalsIgnoreCase(s2)) {
                             if(s2.matches("every Tuesday")){
                                             }else if (s2.matches("every Wednesday")){
                                              }What is wrong with it because I tried to find "every Tuesday" in
    myfile.txt: "Go fishing every Tuesday and every Wednesday"
    There is big problem with split statement because it takes each word not more than a word.
    I need to have "every Tuesday" not "Tuesday". How to make it correct codes?

    I am going to give you a picture of how the output will look.
    Here are two sentences from myfile.txt:
    Go fishing every Tuesday and every Wednesday
    Meet with research students on Thursday
    I need to read from myfile.txt and to find specific words in each sentences like this output:
    Every Tuesday : Go fishing
    Every Wednesday : Go fishing
    Thursday : Meet with research students
    Ok. make sense? Now I am trying to figure out how to find specific words in each sentence from myfile.txt.
    That is why I have difficult with the splits statement and loops. Like this:
           public static String findTheIndex(String sentence){
                String result = "";
                String[] s = sentence.split("\\s");
              for (String s1: s){
                   for (String s2: days){
                        if (s1.equalsIgnoreCase(s2)) {
                             if(s2.matches("every Tuesday")){
                             }else if(s2.matches("every Wednesday")){
                             }else if(s2.matches("Thursday")){
                             }else{
                                  System.out.println("That sentence is not working");
                return result;
      }So look at the "Thursday" it is working the output because I have split statement to give me only one word not more than
    a word in sentence. So there is big problem with more than a word in sentence like this "every Tuesday" and it won't work at all because of split. Could you please help me how to do that? I appreciated for that help. Thanks.

  • Why does Acrobat Pdf converter file slow down my 2003, Windows  Word Program.  I only experience this problem when i convert a pdf file to a doc file.

    Why does Acrobat Pdf converter file slow down my 2003, Windows  Word Program.  I only experience this problem when i convert a pdf file to a doc file.

    Hi Bill -- thanks for your reply!
    When I check the Document Properties on Acrobat I can see that the fonts used in the document (Cambria, Times and Windings) are listed as "Embedded Subset" in the Fonts panel. The machine it was created on did use an earlier version of OS X and an old version of Word, but it seems to have the proper fonts...
    -nick

  • Reading Each String From a text File

    Hello everyone...,
    I've a doubt in File...cos am not aware of File.....Could anyone
    plz tell me how do i read each String from a text file and store those Strings in each File...For example if a file contains "Java Tchnology forums, File handling in Java"...
    The output should be like this... Each file should contains each String....i.e..., Java-File1,Technology-File2...and so on....Plz anyone help me

    The Java� Tutorials > Essential Classes: Basic I/O

  • Read one word at a time from a text file

    I want to read one word at a time from a text file as it is done by "scanf &s" function in text based programme. It is not possible by " read from text"  function. Suggest me  function or method to solve this.

    The simplest way is to use the spreadsheet string to array function with the space character as the delimiter.
    Note that this won't work unless there is a space character between the words - it won't work with line feeds / carriage returns between the words but you could always split the string into lines first. You may also want to trim whitespace to remove any other non-visible characters (e.g. tab, line feeds) from around the word.
    If you need something more sophisticated that splits based on whitespace (e.g. tab, new line) then you'll probably need to do something with searching the string for these characters (e.g. using a regular expression) and then splitting them yourself into an array.
    Of course...if you actually want to just read one word at a time from the file rather than just split the file into words (I assumed you meant this), you will need to read the file byte by byte using the low level file IO functions, build a buffer of the bytes and check the character you've read to see if it a space.
    Certified LabVIEW Architect, Certified TestStand Developer
    NI Days (and A&DF): 2010, 2011, 2013, 2014
    NI Week: 2012, 2014
    Knowledgeable in all things Giant Tetris and WebSockets

  • How to only read the last line in the text file by using BufferedReader ?

    Dear all,
    Hello, I am new to Java. Do anybody know how to read the last line (this is the last record) in the text file.The method I am now using is reading from the first line until I reach the last line in the text file. Thank you!!
    BufferedReader br = new BufferedReader(new FileReader("c:\\sdk1.4.1\\bin\\dbExport.txt"));
    DataInputStream in = new DataInputStream(new FileInputStream("c:\\sdk1.4.1\\bin\\dbExport.txt"));
    String input;
    String firstinput;
    String secondinput;
    int count=90;
    int year=1955;
    while ((input = br.readLine()) != null) {
    firstinput = input.substring(0, 10);
    secondinput = input.substring(10);
    String insertStore1 = ("INSERT INTO AUTHORS " +
    "VALUES ('" + count + "', '" + firstinput + "', '" + secondinput + "', 1955)");
    System.out.println(insertStore1);
    int result = stmt.executeUpdate(insertStore1);

    I suppose you could use a java.io.RandomAccessFile.

  • How to read some lines from a text file using java.

    hi,
    i m new to java and i want to read some lines from a text file based on some string occurrence in the file. This file to be read in steps.
    we only want to read the file upto the first Occurrence of "TEXT" string.
    How to do it ,,,
    Kinldy give the code
    Regards,
    Sagar
    this is the text file
    dfgjdjj
    sfjhjkd
    ghjkdg
    hjkdgh TEXT
    ikeyt
    ujt
    jk
    tyk TEXT
    rukl
    r

    Hendawy wrote:
    Since the word "TEXT" is formed of 4 letters, you would read the text file 4 bytes by four bytes. Wrong on two counts. First, the file may not be encoded 1 byte per character. It could be utf-16 in which case it would be two byte per character. Second, even if it were 1 byte per character, the string "Text" may not start on a 4 byte boundary.
    Consider a FileInputStream object "fis" that points to your text file. use fis.read(byte[] array, int offset, int len) to read every four bytes. Convert the "TEXT" String into a byte array "TEXT".getBytes(), and yous the Arrays class to compare the equality of the read bytes with your "TEXT".getBytes()Wrong since it relies on my second point and will fail when fis.read(byte[] array, int offset, int len) does not read 4 bytes (as is no guaranteed to). Check the Javadoc. Also, the file may not be encoded with the default character encoding.
    The problem is easily solved by reading a line at a time using a BufferedReader wrapping an InputStreamReader wrapping a FileInputStream and specifying the correct character encoding.
    Edited by: sabre150 on Apr 29, 2009 2:13 PM

  • Creating a JButton for each line in a txt file

    I need to know how to creating a JButton for each line in a txt file then add an actionListener to the number of buttons (note they are in a JTable). Here is a clipet of code thanx for the help (note that this is one part of a program i am making there are 2 more classes. If u need them just ask) Thanx:
    class Diary extends JFrame implements ActionListener {
         private JTextArea note;
         private JTextField name;
         private JMenuBar menu = new JMenuBar();
         private JMenu file, edit, font, background, tcolor, settings, help;
         private JMenuItem nu, copy, paste, save, exit, b8, b10, b12, b14, b16, b18, b20, b24, b30, bblue, bred, bgreen, bpink, cblue, cred, cgreen, cpink, eset, nver, using, about;
         private String[] columnNames = {
              "File"
         private Vector dat = new Vector();
         private JTable filetable;
         public Diary() {
              setSize(new Dimension(500, 500));
              setTitle("Diary 2.00");
              file = new JMenu("File");
              menu.add(file);
              nu = new JMenuItem("new");
              nu.addActionListener(this);
              file.add(nu);
              file.add(new JSeparator());
              copy = new JMenuItem("copy");
              copy.addActionListener(this);
              file.add(copy);
              paste = new JMenuItem("paste");
              paste.addActionListener(this);
              file.add(paste);
              file.add(new JSeparator());
              save = new JMenuItem("Save");
              save.addActionListener(this);
              file.add(save);
              file.add(new JSeparator());
              exit = new JMenuItem("exit");
              exit.addActionListener(this);
              file.add(exit);
              edit = new JMenu("Edit");
              menu.add(edit);
              font = new JMenu("font");
              edit.add(font);
              b8 = new JMenuItem("8");
              b8.addActionListener(this);
              font.add(b8);
              b10 = new JMenuItem("10");
              b10.addActionListener(this);
              font.add(b10);
              b12 = new JMenuItem("12");
              b12.addActionListener(this);
              font.add(b12);
              b14 = new JMenuItem("14");
              b14.addActionListener(this);
              font.add(b14);
              b16 = new JMenuItem("16");
              b16.addActionListener(this);
              font.add(b16);
              b18 = new JMenuItem("18");
              b18.addActionListener(this);
              font.add(b18);
              b20 = new JMenuItem("20");
              b20.addActionListener(this);
              font.add(b20);
              b24 = new JMenuItem("24");
              b24.addActionListener(this);
              font.add(b24);
              b30 = new JMenuItem("30");
              b30.addActionListener(this);
              font.add(b30);
              background = new JMenu("background");
              edit.add(background);
              bblue = new JMenuItem("blue");
              bblue.addActionListener(this);
              background.add(bblue);
              bred = new JMenuItem("red");
              bred.addActionListener(this);
              background.add(bred);
              bgreen = new JMenuItem("green");
              bgreen.addActionListener(this);
              background.add(bgreen);
              bpink = new JMenuItem("pink");
              bpink.addActionListener(this);
              background.add(bpink);
              tcolor = new JMenu("text color");
              edit.add(tcolor);
              cblue = new JMenuItem("blue");
              cblue.addActionListener(this);
              tcolor.add(cblue);
              cred = new JMenuItem("red");
              cred.addActionListener(this);
              tcolor.add(cred);
              cgreen = new JMenuItem("green");
              cgreen.addActionListener(this);
              tcolor.add(cgreen);
              cpink = new JMenuItem("pink");
              cpink.addActionListener(this);
              tcolor.add(cpink);
              settings = new JMenu("Settings");
              menu.add(settings);
              eset = new JMenuItem("Edit Settings");
              eset.addActionListener(this);
              settings.add(eset);
              help = new JMenu("Help");
              menu.add(help);
              using = new JMenuItem("Using");
              using.addActionListener(this);
              help.add(using);
              about = new JMenuItem("About");
              about.addActionListener(this);
              help.add(about);
              help.add(new JSeparator());
              nver = new JMenuItem("new Versions");
              nver.addActionListener(this);
              help.add(nver);
              note = new JTextArea("");
              try {
                   BufferedReader filein = new BufferedReader(new FileReader("files.txt"));
                   String sfile;
                   while ((sfile = filein.readLine()) != null) {
                        //add buttons per each line of the txt file and show em
              catch (FileNotFoundException ioe) {
                   JOptionPane.showMessageDialog(null, "Iternal Error, contact [email protected] if the error persists", "", JOptionPane.WARNING_MESSAGE);
              catch (IOException ioe) {
                   JOptionPane.showMessageDialog(null, "Iternal Error, contact [email protected] if the error persists", "", JOptionPane.WARNING_MESSAGE);JOptionPane.showMessageDialog(null, "Iternal Error, contact [email protected] if the error persists", "", JOptionPane.WARNING_MESSAGE);
              String[][] data = new String[dat.size()][];
              for (int x = 0; x < dat.size(); x++) {
                   data[x] = (String[])dat.get(x);
              filetable = new JTable(data, columnNames);
              filetable.setPreferredScrollableViewportSize(new Dimension(100, 500));
              JScrollPane scrollpane = new JScrollPane(filetable);
              name = new JTextField("diary");
              JPanel main = new JPanel(new GridLayout(0, 1));
              getContentPane().add(note);
              getContentPane().add(name, BorderLayout.SOUTH);
              getContentPane().add(scrollpane, BorderLayout.WEST);
              setJMenuBar(menu);
         public void actionPerformed(ActionEvent e) {
              if (e.getSource() == nu) {
                   int nuask = JOptionPane.showConfirmDialog(Diary.this, "Are you sure you want to make a new entry?\nThis will erease any unsaved entry's!!");
                   if (nuask == JOptionPane.YES_OPTION) {
                        note.setText("");
                        note.setBackground(Color.WHITE);
                        note.setForeground(Color.BLACK);
              if (e.getSource() == copy) {
                   note.copy();
              if (e.getSource() == paste) {
                   note.paste();
              if (e.getSource() == save) {
                   try {
                        String sn = name.getText();
                    FileWriter outputStream = new FileWriter("saved/" + sn + ".txt");                            
                    setTitle("Diary 1.00 : " + sn);
                    outputStream.write(note.getText());
                    outputStream.close();
                catch(IOException ioe) {
                     System.out.println("IOException");
              if (e.getSource() == exit) {
                   int exitask = JOptionPane.showConfirmDialog(Diary.this, "Are you sure you want to exit? Any unsaved entries will be deleted");
                   if (exitask == JOptionPane.YES_OPTION) {
                        System.exit(0);
              if (e.getSource() == b8) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),8));
              if (e.getSource() == b10) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),10));
              if (e.getSource() == b12) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),12));
              if (e.getSource() == b14) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),14));
              if (e.getSource() == b18) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),18));
              if (e.getSource() == b20) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),20));
              if (e.getSource() == b24) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),24));
              if (e.getSource() == b30) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),30));
              if (e.getSource() == bblue) {
                   note.setBackground(Color.BLUE);
              if (e.getSource() == bred) {
                   note.setBackground(Color.RED);
              if (e.getSource() == bgreen) {
                   note.setBackground(Color.GREEN);
              if (e.getSource() == bpink) {
                   note.setBackground(Color.PINK);
              if (e.getSource() == cblue) {
                   note.setForeground(Color.BLUE);
              if (e.getSource() == cred) {
                   note.setForeground(Color.RED);
              if (e.getSource() == cgreen) {
                   note.setForeground(Color.GREEN);
              if (e.getSource() == cpink) {
                   note.setForeground(Color.PINK);
              if (e.getSource() == eset) {
                   new UserSettings().setVisible(true);
              if (e.getSource() == about) {
                   JOptionPane.showMessageDialog(null, "Created by Collin Doering 2005 in Gr.9\n\nErrors:\n------------------------------------------------------------------\n1. No File Encryption\n2. No user and password Encryption", "", JOptionPane.INFORMATION_MESSAGE );
              if (e.getSource() == nver) {
                   JOptionPane.showMessageDialog(null, "New Version |3.00| expected July, 2005\n\nNew Features\n----------------------------------------------\n1. File Encryption\n2. User File Encryption\n3. Full help dialog\n4. More Text changing features", "", JOptionPane.INFORMATION_MESSAGE);
              if (e.getSource() == using) {
                   JOptionPane.showMessageDialog(null, "Go ask Collin Doering\[email protected]", "", JOptionPane.INFORMATION_MESSAGE );
    THANK YOU

    so i still do not understand how i would create one
    button per each line in a txt flle then read in the
    file that the txt file specified.This assumes you know how many lines there are in the file.
    If not, modify as per my prior post
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      String[] linesInFile = {"Hello","World","Goodbye","Now"};
      JButton[] btn = new JButton[linesInFile.length];
      public Testing()
        setLocation(200,200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel jp = new JPanel(new GridLayout(0,1));
        for(int x = 0; x < btn.length; x++)
          btn[x] = new JButton(linesInFile[x]);//<---this would be where file.readLine() goes
          jp.add(btn[x]);
          btn[x].addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){
              JOptionPane.showMessageDialog(getContentPane(),ae.getActionCommand());}});
        getContentPane().add(jp);
        pack();
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • How to read every line from a text file???

    How can i read every line from my text file ("eka.txt")
    now it only reads the first line and prints it out.
    What is wrong with this?
    import java.io.*;
    import java.util.*;
    class Testi{
         public static void main(String []args)throws IOException {
         BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
    File inputFile = new File ("eka.txt");
    FileReader fis =new FileReader(inputFile);
    BufferedReader bis = new BufferedReader(fis);
    String test=bis.readLine();
    String tmp= "";
    while((bis.readLine().trim() != null)) {
    int spacefound=0;
    int l=test.indexOf(" ");
         for(int i=0;i<test.length();i++){
         char c=test.charAt(i);
         if(c!=' ') tmp+=""+c;
         if(c==' ' && (spacefound<1) && !(tmp.equals(""))){
         tmp+=""+c;
         spacefound++;
         if(tmp.length()==l) {
         System.out.println(tmp);
         tmp="";
         spacefound=0;
         if(tmp.length()<l){
         for(int i=0;i<=(l-tmp.length());i++)
         tmp+=""+' ';
         System.out.println(tmp);

    Try this code, Hope it servers your purpose.
    import java.io.*;
    import java.util.*;
    class Testi {
         public static void main(String []args)throws IOException {
              BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
              File inputFile = new File ("Eka.txt");
              FileReader fis =new FileReader(inputFile);
              BufferedReader bis = new BufferedReader(fis);
              String test=bis.readLine();
              while(test != null) {
                   StringTokenizer st = new StringTokenizer(test," ");
                   while(st.hasMoreTokens())
                        System.out.println(st.nextToken());
                   test = bis.readLine();
    }Sudha

  • How do i read complete line from a text file in j2me?????

    how do i read complete line from a text file in j2me????? I wanna read file line by line not char by char..Even i tried with readUTF of datainputstream to read word by word but i got UTFDataFormatException.. Please solve my problem.. Thanks in advance..

    That is not my problem . i already read it char by char.. i am getting complete line..But this process is taking to much time..So thats why i directly wanna read complete line or word to save time..

  • Read specified line from a text file

    Hi,
    I am trying to read a specific line from a text file. I don't want to read all of it but just this specific line... say line number 2. Is there a method built-in in java or should I code this myself?
    Thanks and regards,
    Krt_Malta

    Krt_malta wrote:
    I am trying to read a specific line from a text file. I don't want to read all of it but just this specific line... say line number 2. Is there a method built-in in java or should I code this myself?Is there anything in your use case that precludes using the offset of the start of the line rather than the line number?

Maybe you are looking for

  • Cache Notifications unable to determine name of Central Adapter Engine

    Hi All,   When I tried Tools -> Cache Notifications in the integration directory, im getting Unable to determine the name of the central Adapter Engine from the System Landscape Directory at this time. Notifications to the central Adapter Engine are

  • Hello....unable to install flash player on internet explorer 10

    please provide assistance to installing flash player on internet explorer 10... message states please close the following program... internet explorer (installation stop at 50%.

  • Netscape 7.0.2 Error

    Has anyone encountered an error where Netscape won't start up? It says it has unexpectedly quit and error type 2. We tried reinstalling it and restarting neither worked. Also none of the other computers are experiencing this problem. However, another

  • MS Office X to Word 2008

    How do I keep the settings from Word in Office X to Word 2008 for my MacBookPro? The newer software is not opening files exactly the same. Thanks, BF (I can't figure out how to ask a Word discussion site this question. Do they have one? Is it easy to

  • Cant download iOS 5.0

    Cant update my iphone 4 to iOS 5.0, tried everything antivirus to permissions, I can download but then get an error message saying unable to complete. Checked my firewall all okay, is there a way of downloading straight to the iphone without using It