0

So after many many edits to my questions, I am still unable to solve this problem. I have a .txt file called ProcessList.txt which is populated every time ps -e command executes inside my Java app. Here's the code I used to redirect the output of ps -e to ProcessList.txt.

import java.io.*;
import java.util.StringTokenizer;


public class GetProcessList
{

 private String GetProcessListData()
 {
 Process p;
 Runtime runTime;
 String process = null;
 try {
 System.out.println("Processes Reading is started...");

 //Get Runtime environment of System
 runTime = Runtime.getRuntime();

 //Execute command thru Runtime
// p = runTime.exec("tasklist");      // For Windows
 p=runTime.exec("ps -e");              //For Linux

 //Create Inputstream for Read Processes
 InputStream inputStream = p.getInputStream();
 InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

 //Read the processes from sysrtem and add & as delimeter for tokenize the output
 String line = bufferedReader.readLine();
 process = "&";
 while (line != null) {
 line = bufferedReader.readLine();
 process += line + "&";
 }

 //Close the Streams
 bufferedReader.close();
 inputStreamReader.close();
 inputStream.close();

 System.out.println("Processes are read.");
 } catch (IOException e) {
 System.out.println("Exception arise during the read Processes");
 e.printStackTrace();
}
    return process;
 }

 void showProcessData()
 {
 try {

 //Call the method For Read the process
 String proc = GetProcessListData();

 //Create Streams for write processes
 //Given the filepath which you need.Its store the file at where your java file.
 OutputStreamWriter outputStreamWriter =
 new OutputStreamWriter(new FileOutputStream("ProcessList.txt"));
 BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

 //Tokenize the output for write the processes
 StringTokenizer st = new StringTokenizer(proc, "&");

 while (st.hasMoreTokens()) {
 bufferedWriter.write(st.nextToken());  //Write the data in file
 bufferedWriter.newLine();               //Allocate new line for next line
 }

 //Close the outputStreams
 bufferedWriter.close();
 outputStreamWriter.close();

 } catch (IOException ioe) {
 ioe.printStackTrace();
 }

 }
}

It made a file in my workspace called ProcessList.txt. It looks something like this having 4 columns:

1 ?        00:00:00 init
2 ?        00:00:00 kthreadd
3 ?        00:00:00 ksoftirqd/0
5 ?        00:00:00 kworker/u:0
6 ?        00:00:00 migration/0

Now once the ProcessList.txt file is created, I redirected the contents of this .txt file to JTable as:

import java.io.*;
import java.awt.*;
import java.util.*;import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;

public class InsertFileToJtable extends AbstractTableModel{
Vector data;
Vector columns;
private String[] colNames = {"<html><b>PID</b></html>","<html><b>TTY</b></html>","<html><b>time</b></html>","<html><b>Process Name</b></html>",};


public InsertFileToJtable() {
String line;
data = new Vector();
columns = new Vector();
  try {
        FileInputStream fis = new FileInputStream("ProcessList.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
        while (st1.hasMoreTokens())
                columns.addElement(st1.nextToken());
        while ((line = br.readLine()) != null) {
                StringTokenizer st2 = new StringTokenizer(line, " ");
                while (st2.hasMoreTokens())
                       data.addElement(st2.nextToken());
        }
        br.close();
} catch (Exception e) {
        e.printStackTrace();
}  

}

public int getRowCount() {
return data.size() / getColumnCount();
}

public int getColumnCount() {
return columns.size();
}

public Object getValueAt(int rowIndex, int columnIndex) {
return (String) data.elementAt((rowIndex * getColumnCount())
                + columnIndex);
}
@Override
public String getColumnName(int column) {
return colNames[column];
}
@Override
public Class getColumnClass(int col){
return getValueAt(0,col).getClass();
}
}

Here's how my output look so far (I would have uploaded the screen shot of the final output if I knew how to :( but here's a little idea of what the output Jtable looks so far.

=============================
PID  TTY  TIME      PROCESS NAME
=============================
2     ?   00:00:00  kthreadd
3     ?   00:00:00  ksoftirqd/0
5     ?   00:00:00  kworker/u:0
6     ?   00:00:00  migration/0    

Note that the contents of ProcessList.txt get redirected to the JTAble except the fact that the first line of ProcessList.txt file i.e

    1 ?        00:00:00 init

does not seem to be in the JTable output. Any help would be highly appreciated. I have posted many questions about this but came out without luck :(

EDIT: Here's my constructor and main()

public void InterfaceFrame(){
setTitle("My Frame");
add(tabbedPane);
Pack();
setVisible(true);

}

public static void main(String[] args) throws
URISyntaxException,
IOException,
InterruptedException {
    panel.setSize(100,100);
      panel.add(table);
      model.fireTableStructureChanged();

        table.setModel(model);
        InsertFileToJtable model = new InsertFileToJtable();
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
      table.setFillsViewportHeight(true);

      RowSorter<TableModel> sorter =
              new TableRowSorter<TableModel>(model);
            table.setRowSorter(sorter);

        JScrollPane scrollpane = new JScrollPane(table);
        panel.add(scrollpane, BorderLayout.CENTER);

        JButton button = new JButton("Show View");
        panel.add( button, BorderLayout.SOUTH );


        tabbedPane.addTab("Process",null,scrollpane,"");

//////////////SOME OTHER TABS///////////////////////////
}
Ingila Ejaz
  • 399
  • 7
  • 25
  • Your code appears to be reading and discarding the first line of the file. If you don't want it to do that, then change your code. – Hovercraft Full Of Eels Dec 03 '12 at 05:08
  • 1
    *"I have posted many questions about this but came out without luck :("* As mentioned [2 days ago](http://stackoverflow.com/q/13643907/418556), post an [SSCCE](http://sscce.org/). Getting a good answer is rarely about luck. It has more to do with asking a good question, and that often involves code in the form of an SSCCE. – Andrew Thompson Dec 03 '12 at 05:18
  • @HovercraftFullOfEels "If you don't want it to do that, then change your code" That's what my question is. – Ingila Ejaz Dec 03 '12 at 05:23
  • @AndrewThompson please check the edits and let me know if you can help atleast this time. – Ingila Ejaz Dec 03 '12 at 05:35
  • 1. to check oracle tutorial How is created JTableHeader, simple not, remove Html tags – mKorbel Dec 03 '12 at 05:47
  • 2. ksoftirqd/0 did you able to printout by using System.out.println(), isn't this block escaped – mKorbel Dec 03 '12 at 05:49
  • 3. whatever.close(); should be in finally block, add this after catch – mKorbel Dec 03 '12 at 05:49
  • @mKorbel what is meant by "whatever"? – Ingila Ejaz Dec 03 '12 at 05:56
  • `bufferedReader.close();`, `inputStreamReader.close();`, `inputStream.close();`, `br.close();` :-), I' too lazy to search for more – mKorbel Dec 03 '12 at 06:00

1 Answers1

1

[…] the contents of ProcessList.txt get redirected to the JTAble except the fact that the first line of ProcessList.txt file […] does not seem to be in the JTable output.

This is because you're reading the first row to the columns vector, all others to the data vector. I assume the core from which you adopted this used an input file with a header line. Simply read everything into data, and just count the columns in an integer to obtain the column count.

For example, you could edit your code like this, with -indicating removed lines and + indicating added ones.

 public class InsertFileToJtable extends AbstractTableModel{
 Vector data;
-Vector columns;
+int columnCount;
⋮
 data = new Vector();
-columns = new Vector();
+coumnCount = 0;
⋮
-        while (st1.hasMoreTokens())
-                columns.addElement(st1.nextToken());
+        while (st1.hasMoreTokens()) {
+                data.addElement(st1.nextToken());
+                ++coumnCount;
+        }
⋮
 public int getColumnCount() {
-return columns.size();
+return coumnCount;
 }
MvG
  • 57,380
  • 22
  • 148
  • 276
  • try { FileInputStream fis = new FileInputStream("ProcessList.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); StringTokenizer st1 = new StringTokenizer(br.readLine(), " "); while (st1.hasMoreTokens()) data.addElement(st1.nextToken()); while ((line = br.readLine()) != null) { StringTokenizer st2 = new StringTokenizer(line, " "); while (st2.hasMoreTokens()) data.addElement(st2.nextToken()); } br.close(); } catch (Exception e) { e.printStackTrace(); } } I did this but it catches exception that: Exception in thread "main" java.lang.ArithmeticException: / by zero – Ingila Ejaz Dec 03 '12 at 07:50
  • 1
    @IngilaEjaz: Please update you question with new code; it's hard to read in a comment – trashgod Dec 03 '12 at 08:58