please consider the following file of given staff.

Bob
100100653
5860
London
H3ll0
1

How do i extract the 6th line for multiple files and generate a report in java for each files under same directory? the above is just one file data. i want to read multiple files and extract 6th line for each files on click of a buttonS?

Recommended Answers

All 30 Replies

How do i extract the 6th line for multiple files

Read through the first six lines and save the last line read.
If the sixth line is at the same offset in all the files you could use a RandomAccessFile to read the last line without reading the preceding lines.

is there any way of extracting line information and then use the mail merge facility to link the extraction data to word and generate a letter of sort to staff members. i want to extract some of the file information into a letter on click of a button.

way of extracting line information

If the line is in a String, the String class has many methods for extracting information.
Can you show an example of the lines and the information that you want to get from the lines?

i want extracting is all lines except line 3.

That should be no problem. When you are reading the lines, skip saving line number 3.

ok thanks, in the case of multiple files in the same directory, how will you code to read each files one by one.

The File class has a method to get a list of all the files in a directory. You can use that list of files to read the files one by one.

public class calcBalanceListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			 FileReader fileReader = null;
		        BufferedReader bufferedReader = null;
		        try {
		            File folder = new File("C:/Users/Mahady/Desktop/Java 31122011/src/register/");
		            if (folder.isDirectory()) {
		                for (File file : folder.listFiles()) {
		                    fileReader = new FileReader(file);
		                    bufferedReader = new BufferedReader(fileReader);
		                    String name = bufferedReader.readLine();
		                    String id = bufferedReader.readLine();
		                    bufferedReader.readLine(); //omit pin
		                    String address = bufferedReader.readLine();
		                    String carReg  = bufferedReader.readLine();
		                    String balance = bufferedReader.readLine();
		                    bufferedReader.readLine(); //omit lost or stolen id
		                    
		                    

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

Hello, I want to show individual records within a frame, but not all together. I would like some sort of navagation 'next' button to show the next record. any idea on how to create this? its like viewing different staff data but not all on the same page. require having a previous and next buttons?

I want to show individual records within a frame

A simple way would be to use a text area. Set its contents to the record you want to show.
Use the buttons to navigate forward and backwards through the file.
Disable the buttons when there is no record in that direction. For example when the first record is shown, disable the Previous button.

A simple way would be to use a text area. Set its contents to the record you want to show.
Use the buttons to navigate forward and backwards through the file.
Disable the buttons when there is no record in that direction. For example when the first record is shown, disable the Previous button.

perhaps can you show me an example using code? i am reading file content for all files into a variable as you can see. in what way can i transfer this to the textarea you are talking of.

thanks

If the variable is a String, the JTextArea class has a method you can call to put the contents of the String into the text area.

If the variable is a String, the JTextArea class has a method you can call to put the contents of the String into the text area.

ok instead i am using arraylist to hold path address, but how do i use global counter to navigate the arraylist and increment the counter based on next and previous button?

public class calcBalanceListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			    FileReader fileReader = null;
		        BufferedReader bufferedReader = null;
		        try {
		            File folder = new File("/register/");
		            ArrayList<String> filePaths = new ArrayList<String>();
		            if (folder.isDirectory()) {
		                                for (File file : folder.listFiles()) {
		                                    filePaths.add(file.getPath());
		                                    }
		                                }
		        }//end try
		        
		        catch (Exception f) {
		        	f.printStackTrace();
			      } 
		        
		
				}}

how do i use global counter to navigate the arraylist and increment the counter based on next and previous button

If the global counter points to the current item being displayed, the next button should add 1 to it and the previous button should subtract 1 from it to get the index of the item to display.

How does the posted code relate to your question?

it does relate in terms of playing with multiple files. the filepath arraylist hold path address, how i print the actual file contents?

how i print the actual file contents?

Sorry, I don't see the problem.
Read the file line by line and print the lines you want printed.

/*********************Calcculate Staff Balance***************************/  
public class calcBalanceListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {

        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        try {
            File folder = new File("/register/");
           filePaths = new ArrayList<String>();
            if (folder.isDirectory()) {
                                for (File file : folder.listFiles()) {
                                    filePaths.add(file.getPath());
                                    }
            }

        }//end try

        catch (Exception f) {
            f.printStackTrace();
          } 


            }}
/*****************************************/

public void callDetail() {


    File f = new File(filePaths.get(indexCounter));
    try{
        FileReader fileReader = new FileReader(f);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String name = bufferedReader.readLine();
        String id = bufferedReader.readLine();
        bufferedReader.readLine();
        String address = bufferedReader.readLine();
        String amount = bufferedReader.readLine();
        bufferedReader.readLine();

        bufferedReader.close();
        fileReader.close();

    }//end try
    catch(IOException z){

        z.printStackTrace();
    }   //end catch     


}

Will you suggest any correction. i cannot get it to update labels and generate the frame.

i cannot get it to update labels and generate the frame.

I don't see any labels or any frame.
You will need to post some code that shows the problem you are having.

I don't see any labels or any frame.
You will need to post some code that shows the problem you are having.

/*********************Calcculate Staff Balance***************************/	
	public class calcBalanceListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			    
			FileReader fileReader = null;
	        BufferedReader bufferedReader = null;
	        try {
	            File folder = new File("/register/");
	           filePaths = new ArrayList<String>();
	            if (folder.isDirectory()) {
	                                for (File file : folder.listFiles()) {
	                                    filePaths.add(file.getPath());
	                                    }
	            }
	            
	        }//end try
	        
	        catch (Exception f) {
	        	f.printStackTrace();
		      } 
		
	        	callDetail();
				}}
/*************************************************************************/

	
	
	
	public void callDetail() {


	    File f = new File(filePaths.get(indexCounter));
	    try{
	        FileReader fileReader = new FileReader(f);
	        BufferedReader bufferedReader = new BufferedReader(fileReader);
	        String name = bufferedReader.readLine();
	        int id = Integer.parseInt(bufferedReader.readLine());
	        bufferedReader.readLine();
	        String address = bufferedReader.readLine();
	        int amount = Integer.parseInt(bufferedReader.readLine());
	        bufferedReader.readLine();
	        
	        balanceFrame = new JFrame("Monthly Staff Balance");
	        
	        	lID.setText("Staff ID: " + id);
	        	lname.setText("Staff ID: " + name);
	        	laddress.setText("Staff ID: " + address);
	        	lbalance.setText("Staff ID: " + amount);
	        	
	        
	        	balanceFrame.add(lID);
	        	balanceFrame.add(lname);
	        	balanceFrame.add(laddress);
	        	balanceFrame.add(lbalance);

	        bufferedReader.close();
	        fileReader.close();

	    }//end try
	    catch(IOException z){

	        z.printStackTrace();
	    }   //end catch     


	}
/***************************************************************************************************/

apologies for that, the errors are

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Inde
x: 0, Size: 0
        at java.util.ArrayList.RangeCheck(Unknown Source)
        at java.util.ArrayList.get(Unknown Source)
        at Main_GUI.callDetail(Main_GUI.java:138)
        at Main_GUI$calcBalanceListener.actionPerformed(Main_GUI.java:128)
        at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
        at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Sour
ce)
        at java.awt.Component.processMouseEvent(Unknown Source)
        at javax.swing.JComponent.processMouseEvent(Unknown Source)
        at java.awt.Component.processEvent(Unknown Source)
        at java.awt.Container.processEvent(Unknown Source)
        at java.awt.Component.dispatchEventImpl(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Window.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.EventQueue.dispatchEvent(Unknown Source)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.run(Unknown Source)

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Inde
x: 0, Size: 0
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Main_GUI.callDetail(Main_GUI.java:138)

At line 318 in Main_GUI the code tries to get the first(Index: 0) element in an array that is empty (Size: 0)

You need to test if the arraylist has any contents before trying to get elements from it.

couldnt solve it? arraylist doesnt print either. i have added elements to it but print statement in for loop didnt print anything. maybe its the problem with gui.

i have added elements to it

Are you sure? The JVM finds it empty.
Did you double check that it was not empty?
Print out its size or just print the arraylist itself to show what is in it.

for (int i = indexCounter; i<filePaths.size(); i++){
				
				System.out.println(filePaths.get(i));
			}

yes i did this statement and print the directory of the files which i added to array list. but as stated earlier, in the gui generation i am having problem with. problems in relation to callDetail() method.

Your code is assuming there some entries in filePaths.
Try just printing filePaths: S.o.println("fp=" + filePaths)
If filePaths is empty, the loop won't execute

Here you are assuming there is an array returned by listFiles():
for (File file : folder.listFiles()) {

filePaths is not empty. filePaths is arraylist, and it holds all the filepaths of the staff files. and it printed as i just tested it.

Then why does the JVM give this error message:

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Inde
x: 0, Size: 0
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Main_GUI.callDetail(Main_GUI.java:138)

That says there is an empty array.
Print out the contents of that array to prove what is in it.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at Main_GUI.callDetail(Main_GUI.java:158)
        at Main_GUI$calcBalanceListener.actionPerformed(Main_GUI.java:132)
        at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
        at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Sour
ce)
        at java.awt.Component.processMouseEvent(Unknown Source)
        at javax.swing.JComponent.processMouseEvent(Unknown Source)
        at java.awt.Component.processEvent(Unknown Source)
        at java.awt.Container.processEvent(Unknown Source)
        at java.awt.Component.dispatchEventImpl(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Window.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.EventQueue.dispatchEvent(Unknown Source)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.run(Unknown Source)

C:\Users\Mahady\Desktop\Java 31122011\src>

C:\Users\Mahady\Desktop\Java 31122011\src>

C:\Users\Mahady\Desktop\Java 31122011\src>javac *.java

this is the new error after code changes.

/*********************Calculate Staff Balance***************************/	
	public class calcBalanceListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			    
			FileReader fileReader = null;
	        BufferedReader bufferedReader = null;
	        try {
	            File folder = new File("C:/Users/Mahady/Desktop/Java 31122011/src/register/");
	           filePaths = new ArrayList<String>();
	            if (folder.isDirectory()) {
	                                for (File file : folder.listFiles()) {
	                                    filePaths.add(file.getPath());
	                                    }
	            }
	            
	        }//end try
	        
	        catch (Exception f) {
	        	f.printStackTrace();
		      } 
			for (int i = indexCounter; i<filePaths.size(); i++){
				
				System.out.println(filePaths.get(i));
			}
			
			callDetail();
			
	        	
				}}
/*************************************************************************/

	
	
	
	public void callDetail() {


	    File f = new File(filePaths.get(indexCounter));
	    try{
	        FileReader fileReader = new FileReader(f);
	        BufferedReader bufferedReader = new BufferedReader(fileReader);
	        String name = bufferedReader.readLine();
	        int id = Integer.parseInt(bufferedReader.readLine());
	        bufferedReader.readLine();
	        String address = bufferedReader.readLine();
	        String carReg = bufferedReader.readLine();
	        int amount = Integer.parseInt(bufferedReader.readLine());
	        bufferedReader.readLine();
	        
	        balanceFrame = new JFrame("Monthly Staff Balance");
	        
	        	lID.setText("Staff ID: " + id);
	        	lname.setText("Staff ID: " + name);
	        	laddress.setText("Staff ID: " + address);
	        	lbalance.setText("Staff ID: " + amount);
	        	
	        
	        	balanceFrame.add(lID);
	        	balanceFrame.add(lname);
	        	balanceFrame.add(laddress);
	        	balanceFrame.add(lbalance);
	        	
	        	balanceFrame.setVisible(true);
	        	balanceFrame.setSize(400, 400);

	        bufferedReader.close();
	        fileReader.close();

	    }//end try
	    catch(IOException z){

	        z.printStackTrace();
	    }   //end catch     


	}
/***************************************************************************************************/

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Main_GUI.callDetail(Main_GUI.java:158)
at Main_GUI$calcBalanceListener.actionPerformed(Main_GUI.java:132)

There is a null variable at line 158 in the callDetail method.
Look at that line and see what variable could be null. Then backtrack in the code to see why it does not have a valid value. If you can not see which variable is null, add a println just before the line 158 and print out the values of all the variables used on that line.

i have almost reached the end, but the previous button shows record but displays error after clicking it more times

public class buttonListener implements ActionListener {
		 public void actionPerformed(ActionEvent x){
		        if (x.getSource() == nxtButton){
		  
		            indexCounter++;
		            balanceFrame.setVisible(false);
		            callDetail();
		 
		            if(indexCounter == filePaths.size()-1) { //max counter...we dont want to exceed the max number, size of array
		            	indexCounter = -1;
		           
		    }
		    }
		        else if (x.getSource() == prevButton){
		        	indexCounter--;
		        	balanceFrame.setVisible(false);
		        	callDetail();
		        		if(indexCounter == 0){
		        			indexCounter = filePaths.size()-1;
		        		}
		        }

		}}

whats the problem with previous buttton

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.