Hi Sachith,
I hv done this Program for some networking purposes, but u can see
this program handling the files (JPingConf.txt, JPingLog.txt)
dynamically,
hope this will help you...
i hate this word wrap while sending a mail, program's readability
totally spoils :-(
regards,
S.Vasanth Kumar.
import java.awt.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.swing.table.*;
import java.text.SimpleDateFormat;
public class JPing extends JFrame implements ActionListener,Runnable
{
JLabel jlblTitle = new JLabel("JPing v1.0", JLabel.CENTER);
JTable jtblIP;
Vector vContents = new Vector();
String strHeadings[] = {"DOMAIN","IP ADDRESS","PORT","LAST CHECK
TIME","STATUS"};
String STRING_HI = "JPing-Hi, This Message Will be sent to each &
every the Destination to check Connectivity!!";
JTextField jtfRegion = new JTextField(10);
JTextField jtfIP = new JTextField(15);
JTextField jtfPort = new JTextField(4);
JButton jbtnAdd = new JButton("Add");
JButton jbtnSave = new JButton("Save");
Container c = getContentPane();
GridBagLayout grid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
SimpleDateFormat sdfNormal = new SimpleDateFormat("dd/MM/yyyy
hh:mm:ss a");
Thread thrdRun;
boolean thrdFlag=true,initFlag=true;
String strConfFile = "JPingConf.txt";
String strLogFile = "JPingLog.txt";
int errX=0,errY=-30;
public JPing()
{
super("JPing v1.0");
setSize(725,500);
jtfPort.setText("23");
IPModel tmIPModel = new IPModel();
jtblIP = new JTable(tmIPModel);
jtblIP.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jtblIP.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
jtblIP.setRowHeight(jtblIP.getRowHeight()+3);
buildTable();
doDataCollection();
thrdRun = new Thread(this);
thrdRun.start();
JPanel jpnlSouth = new JPanel(new FlowLayout(FlowLayout.CENTER));
jpnlSouth.add(new JLabel("Region: ",JLabel.RIGHT));
jpnlSouth.add(jtfRegion);
jpnlSouth.add(new JLabel("IP: ",JLabel.RIGHT));
jpnlSouth.add(jtfIP);
jpnlSouth.add(new JLabel("Port: ",JLabel.RIGHT));
jpnlSouth.add(jtfPort);
jpnlSouth.add(jbtnAdd);
jpnlSouth.add(jbtnSave);
jlblTitle.setFont(new Font("Dialog",Font.BOLD,20));
c.setLayout(grid);
gbc.fill = gbc.BOTH;
gbc.insets = new Insets(2,2,2,2);
addComponent(jlblTitle,0,0,2,1);
gbc.weightx=1;
gbc.weighty=1;
addComponent(new JScrollPane(jtblIP),1,0,1,1);
gbc.weightx=0;
gbc.weighty=0;
addComponent(jpnlSouth,2,0,1,1);
validate();
setVisible(true);
jbtnAdd.addActionListener(this);
jbtnSave.addActionListener(this);
jbtnAdd.setMnemonic('A');
jbtnSave.setMnemonic('S');
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
try
{
thrdFlag = false;
doAppendLog("\r\nProgram Exited on " + sdfNormal.format(new Date
()));
dispose();
}
catch(Exception ex){}
finally
{
System.exit(0);
}
}
});
jtblIP.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode() == ke.VK_DELETE)
{
int row = jtblIP.getSelectedRow();
for(int i=0;i<jtblIP.getColumnCount();i++)
jtblIP.setValueAt("",row,i);
jtblIP.repaint();
}
}
});
try
{
doAppendLog("\r\nProgram Started on " + sdfNormal.format(new Date
()));
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this,ex.toString
(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
public void addComponent(Component ct,int y,int x,int width,int
height)
{
gbc.gridx=x;
gbc.gridy=y;
gbc.gridwidth=width;
gbc.gridheight=height;
grid.setConstraints(ct,gbc);
c.add(ct);
}
public void buildTable()
{
jtblIP.createDefaultColumnsFromModel();
StatusRenderer srRenderer = new StatusRenderer();
TableColumnModel tcm = jtblIP.getColumnModel();
tcm.getColumn(4).setCellRenderer(srRenderer);
tcm.getColumn(0).setPreferredWidth(100);
tcm.getColumn(1).setPreferredWidth(75);
tcm.getColumn(2).setPreferredWidth(50);
tcm.getColumn(3).setPreferredWidth(160);
tcm.getColumn(4).setPreferredWidth(200);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == jbtnAdd)
{
try
{
if(jtfRegion.getText().trim().equalsIgnoreCase(""))
JOptionPane.showMessageDialog(this,"Please enter a valid
Region...","Warning",JOptionPane.WARNING_MESSAGE);
else if(jtfIP.getText().trim().equalsIgnoreCase(""))
JOptionPane.showMessageDialog(this,"Please enter a valid
IP...","Warning",JOptionPane.WARNING_MESSAGE);
else if(Integer.parseInt(jtfPort.getText().trim())<0)
JOptionPane.showMessageDialog(this,"Please enter a valid
Port...","Warning",JOptionPane.WARNING_MESSAGE);
else
{
vContents.add(jtfRegion.getText().trim().toUpperCase());
vContents.add(jtfIP.getText().trim().toUpperCase());
vContents.add(jtfPort.getText().trim());
vContents.add("");
vContents.add("");
jtblIP.repaint();
jtblIP.revalidate();
jtfRegion.setText("");
jtfIP.setText("");
jtfPort.setText("23");
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this,ex.toString
(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
else if(ae.getSource() == jbtnSave)
{
try
{
StringBuffer sb = new StringBuffer();
for(int i=0;i<jtblIP.getRowCount();i++)
{
if(jtblIP.getValueAt(i,1).toString().trim().equalsIgnoreCase(""))
continue;
if(i>0)
sb.append("\r\n");
for(int j=0;j<jtblIP.getColumnCount();j++)
{
if(j>0)
sb.append("\t");
String strTemp = jtblIP.getValueAt(i,j).toString().trim();
if(strTemp.equalsIgnoreCase(""))
strTemp = "-";
sb.append(strTemp);
}
}
OutputStream out = new FileOutputStream(strConfFile);
out.write(sb.toString().trim().getBytes());
out.flush();
out.close();
doDataCollection();
JOptionPane.showMessageDialog(this,"Configuration Saved
Successfully", "Save", JOptionPane.INFORMATION_MESSAGE);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this,ex.toString
(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
}
public void doDataCollection()
{
try
{
File f = new File(strConfFile);
if(!f.isFile())
f.createNewFile();
BufferedReader brReader = new BufferedReader(new FileReader
(strConfFile));
vContents.removeAllElements();
String strLine=null;
while((strLine = brReader.readLine())!=null)
{
StringTokenizer st = new StringTokenizer(strLine,"\t");
while(st.hasMoreTokens())
{
vContents.add(st.nextToken());
}
}
jtblIP.repaint();
jtblIP.revalidate();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this,ex.toString
(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
public void run()
{
if(Thread.currentThread() == thrdRun)
{
while(thrdFlag)
{
int i=0;
for(i=0;i<jtblIP.getRowCount();i++)
{
if(jtblIP.getValueAt(i,1).toString().trim().equalsIgnoreCase(""))
continue;
boolean errShow = false;
if(jtblIP.getValueAt(i,4).toString().trim().equalsIgnoreCase
("Ok") || jtblIP.getValueAt(i,4).toString().trim().equalsIgnoreCase
("") || jtblIP.getValueAt(i,4).toString().trim().equalsIgnoreCase("-
"))
errShow = true;
boolean logAppend = false;
if(!jtblIP.getValueAt(i,4).toString().trim().equalsIgnoreCase
("Ok") && !jtblIP.getValueAt(i,4).toString().trim().equalsIgnoreCase
("") && !jtblIP.getValueAt(i,4).toString().trim().equalsIgnoreCase("-
"))
logAppend = true;
try
{
Socket s = new Socket(jtblIP.getValueAt(i,1).toString().trim
(),Integer.parseInt(jtblIP.getValueAt(i,2).toString().trim()));
OutputStream out = s.getOutputStream();
out.write(STRING_HI.getBytes());
out.flush();
out.close();
s.close();
jtblIP.setValueAt(sdfNormal.format(new Date()),i,3);
jtblIP.setValueAt("Ok",i,4);
if(logAppend)
{
doRowLog(i);
}
}
catch(Exception ex)
{
try
{
jtblIP.setValueAt(sdfNormal.format(new Date()),i,3);
jtblIP.setValueAt(ex.toString(),i,4);
if(errShow || initFlag)
{
initFlag = false;
doRowLog(i);
if(errY>=300)
{
errY = 0;
errX += 50;
}
else
{
errY += 30;
}
JFrame jfError = new JFrame(jtblIP.getValueAt(i,0).toString()
+ " - Problem");
jfError.setResizable(false);
jfError.setLocation(errX,errY);
JTextArea jtaError = new JTextArea(5,35);
jtaError.setLineWrap(true);
jtaError.setWrapStyleWord(true);
jtaError.setEditable(false);
jtaError.setText(jtblIP.getValueAt(i,0).toString() + " having
problem (" + ex.toString() + ")\r\nTime: " + jtblIP.getValueAt
(i,3).toString().trim() + "\r\nIP: " + jtblIP.getValueAt(i,1).toString
().trim() + ", Port: " + jtblIP.getValueAt(i,2).toString().trim());
jfError.getContentPane().add("Center",new JScrollPane
(jtaError));
jfError.validate();
jfError.pack();
jfError.show();
jfError.toFront();
}
}
catch(ArrayIndexOutOfBoundsException aioobEx){}
catch(Exception exIO)
{
JOptionPane.showMessageDialog(this,exIO.toString
(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
finally
{
jtblIP.repaint();
}
}
try
{
thrdRun.sleep(30000);
}catch(Exception ex){}
}
}
}
public void doAppendLog(String str) throws IOException
{
OutputStream out = new FileOutputStream(strLogFile,true);
out.write(str.getBytes());
out.flush();
out.close();
}
public void doRowLog(int i) throws IOException
{
StringBuffer sb = new StringBuffer();
sb.append("\r\n");
for(int j=0;j<jtblIP.getColumnCount();j++)
{
if(j>0)
sb.append("\t");
String strTemp = jtblIP.getValueAt(i,j).toString().trim();
if(strTemp.equalsIgnoreCase(""))
strTemp = "-";
sb.append(strTemp);
}
doAppendLog(sb.toString());
}
public static void main(String args[])
{
new JPing();
}
class IPModel extends AbstractTableModel
{
public int getColumnCount()
{
return strHeadings.length;
}
public String getColumnName(int col)
{
return strHeadings[col];
}
public int getRowCount()
{
return vContents.size()/strHeadings.length;
}
public void setValueAt(Object value, int row, int col)
{
vContents.setElementAt(value,(row*strHeadings.length)+col);
}
public Object getValueAt(int row,int col)
{
return vContents.elementAt((row*strHeadings.length)+col);
}
public boolean isCellEditableAt(int row,int col)
{
return false;
}
}
class StatusRenderer extends DefaultTableCellRenderer
{
public void setValue(Object str)
{
super.setValue(str);
if(str.toString().trim().toUpperCase().equalsIgnoreCase("Ok"))
setBackground(Color.green.darker());
else
setBackground(Color.red.brighter());
}
public Font getFont()
{
return new Font("Dialog",Font.BOLD,14);
}
}
}
--- Sachith Dassanayake <[EMAIL PROTECTED]> wrote:
>
>
> Dear Vasanth Kumar,
>
> Thank you very much for your reply. You are correct.
> It was the
> mistake I have done. I have recieved 3 emails
> regarding to this.
>
> I want to display the records which are stored in
> the file in a
> table or a lJList. I tryed but I couldn't do it
> Dynamically.
> Can U help me On this.
> This I'm doing for my assignment and I have to
> sumbmit it on
> Friday.
> Sorry for troubling you.
>
> Thank you once again
> Regards
> Sachith
>
> Vasanth Kumar writes:
>
> >
> >
> > Hi Sachith,
> >
> > If you are using FileOutputStream to store your
> data,
> > you have to use the constructor as follows
> >
> > FileOutputStream("OutFile.txt", true)
> >
> > But if u are using FileOutputStream("OutFile.txt")
> the
> > default behavior will OVERWRITE ur file whenever u
> > call FileOutputStream.write() method.
> >
> > so pass "true" as second argument, means do you
> want
> > to append to the file ??? "YES"
> >
> > regards,
> > S.Vasanth Kumar.
> >
> > import java.io.*;
> > import java.util.Date;
> >
> > public class AppendDemo
> > {
> > public static void main(String args[])
> > {
> > try
> > {
> > OutputStream out = new
> > FileOutputStream("AppendLog.txt", true); // true
> here
> > is v.v.imp to append the future contents
> > out.write(("Program executed on: " + new Date()
> +
> > "\r\n").getBytes());
> > out.flush();
> > out.close();
> > }
> > catch(Exception ex)
> > {
> > System.out.println(ex.toString());
> > }
> > }
> > }
> >
> > --- Sachith Dassanayake <[EMAIL PROTECTED]>
> wrote:
> >>
> >>
> >> I 'm doing a simple program on file handling in
> >> JAVA.
> >> I need to store 3 data
> >>
> >> 1 First Name
> >> 2 Last Name
> >> 3 Phone Number
> >> in to a file. (Not
> a
> >> Database). I
> >> tryed to do it using
> >> datainputstreams etc.. But when i enter the
> second
> >> record it
> >> over writes the first record.
> >> How can i over ome this problem
> >>
> >> Also I hav to display all the records in a table
> >> after entering.
> >> It has to be worked even I close the program and
> >> reopen it.
> >>
> >> It would be greatful if any one can help me on my
> >> program.
> >>
> >> Thank you
> >> Sachith
> >> ---------------------------------------------
> >> Free POP3 Email from www.Gawab.com
> >> Sign up NOW and get your account @gawab.com!!
> >>
> >>
> >> [Non-text portions of this message have been
> >> removed]
> >>
> >>
> >>
> >>
> >>
> >
> >
>
______________________________________________________________________
__
> > Yahoo! India Matrimony: Find your partner online.
> http://yahoo.shaadi.com/india-matrimony/
> >
> >
> >
> >
> >
> > ------------------------ Yahoo! Groups Sponsor
> --------------------~-->
> > $9.95 domain names from Yahoo!. Register anything.
> >
> http://us.click.yahoo.com/J8kdrA/y20IAA/yQLSAA/5cFolB/TM
> >
> --------------------------------------------------------------------
~->
>
> >
> > If you have any comments or questions, submit it
> on the message board.
> > NO spam/ads/job posting or you will be BANNED from
> this group. Exception can be made it happen by
> notify me ahead of time.
> > all new members' message will be verified by me
> (spam..) before it get posted.
> > Yahoo! Groups Links
> >
> >
> > [EMAIL PROTECTED]
> >
> >
> >
> >
> >
>
> ---------------------------------------------
> Free POP3 Email from www.Gawab.com
> Sign up NOW and get your account @gawab.com!!
>
------------------------ Yahoo! Groups Sponsor --------------------~-->
Make a clean sweep of pop-up ads. Yahoo! Companion Toolbar.
Now with Pop-Up Blocker. Get it for free!
http://us.click.yahoo.com/L5YrjA/eSIIAA/yQLSAA/5cFolB/TM
--------------------------------------------------------------------~->
If you have any comments or questions, submit it on the message board.
NO spam/ads/job posting or you will be BANNED from this group. Exception can be made
it happen by notify me ahead of time.
all new members' message will be verified by me (spam..) before it get posted.
Yahoo! Groups Links
<*> To reply to this message, go to:
http://groups.yahoo.com/group/java_official/post?act=reply&messageNum=17270
Please do not reply to this message via email. More information here:
http://help.yahoo.com/help/us/groups/messages/messages-23.html
<*> To visit your group on the web, go to:
http://groups.yahoo.com/group/java_official/
<*> To unsubscribe from this group, send an email to:
[EMAIL PROTECTED]
<*> Your use of Yahoo! Groups is subject to:
http://docs.yahoo.com/info/terms/