Hi, im fairly new to Java, learning as I go on. I have gotten to the stage that I need to read specific lines from a text file that has already been created.

Lets say my text document has 30 lines, and I only want to read what is in the 5th line without needing to read any other line. How would I go about doing this. I have looked on the forums and there is a lot of code but i dont understand most of it and dont know which is the better solution for me.
What I want to do is, open the file, read the 5th line as a string which i will later on use to compare with other strings to run different methods.

Also, how would i go about reading the last 5 lines of that text file but I do not know the number of lines that text file will have since in my code that will be created will be writing more lines into the text file, so i need the code to find the 5th to last line and read from there the contents which will later be printed out in a textbox.

Thanks to anyone that can help me out or point me in the right direction.

Recommended Answers

All 8 Replies

import java.io.*;
import java.util.Scanner;


public class Main {


    public static void main(String[] args) {


         Process(5);
      
           }


    public static void Process(int number)
    {
      try{
           FileReader file1 = new FileReader("input.txt");
           BufferedReader f = new BufferedReader(file1);
           String temp;
           int i =0 ;
           while((temp=f.readLine())!=null)
           {
               i++;

               if(i==5)
               {
                  System.out.println(temp);
               }


           }
      }

      catch(Exception e)
      {}

    }

}

This code only reads the 5th line, you can change it the way you want. However if you want additional features then you might want to look at "&&" operator and conditional loops. Hope this helps.

I've tried the code above but it doesn't seem to work. This is what im trying to accomplish to then edit into my proper code, this is just to test.

This is what I have at the moment

import java.awt.*;

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

public class TextFileTest extends JFrame implements ActionListener {

	private static JTextArea miniStatementScreen;
	private JLabel status;
	private JTextField username;
	private JTextField password;
	//JPasswordfield
	private String customerID = "12345"; // Default ID for the customer
	private String name = "Carlos"; // default
	
	
	
	public TextFileTest() {
		super ("ATM Project GUI");
		initMenu();
		initTop();
		initMiddle();
		initBottom();
		pack();
		setSize(600,600);
	    setResizable(false);
	    setVisible(true);
		
	}

	private void initMenu(){
		JMenuBar menuBarObject = new JMenuBar();
		JMenu options = new JMenu("Options");
		menuBarObject.add(options);
		JMenuItem exit = new JMenuItem("Exit");
		
		exit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent c) {
            	System.exit(0);
            }
        });
		//options.add(backToMenu);
		
		options.add(exit);		
		setJMenuBar(menuBarObject);
		
	}
	

	private void initTop() {
	
		JPanel staticText = new JPanel();
		staticText.setLayout(new BorderLayout());
		JLabel label = new JLabel("Welcome Screen");
		label.setHorizontalAlignment(JLabel.CENTER);
		staticText.add(label, BorderLayout.CENTER);
		add(staticText, BorderLayout.NORTH);
		
	}

	private void initMiddle() {
		
		JPanel userpass = new JPanel();
		userpass.setLayout(new GridLayout(2,4));
		username = new JTextField();
		JLabel usernameText = new JLabel("Enter Username:");
		userpass.add(usernameText);
		userpass.add(username);
		
		password = new JTextField();
		//JPasswordfield
		Label passwordText = new Label("Enter Password:");
	
		userpass.add(passwordText);
		userpass.add(password);
		
		add(userpass, BorderLayout.CENTER);
		
	}
	

	private void initBottom(){
		JPanel login = new JPanel();

		login.setLayout(new GridLayout(3,1)); //2rows, 1columns
		JButton loginButton = new JButton("Login");
		loginButton.addActionListener(this);
		login.add(loginButton,BorderLayout.NORTH);
		status = new JLabel("");
		status.setHorizontalAlignment(JLabel.CENTER);
		login.add(status,BorderLayout.CENTER);
		miniStatementScreen = new JTextArea(10,10);
		miniStatementScreen.setEditable(false);
		login.add(miniStatementScreen,BorderLayout.SOUTH);
		add(login, BorderLayout.SOUTH);
		
	}
	
	
 public void actionPerformed(ActionEvent e) {
	 String checkUsername = username.getText();
	 String checkPassword = password.getText();
	 if (checkUsername.equals(name) && (checkPassword.equals(customerID)))
	 {
	 lineReader();
	 //opening new Gui & closing the previous one
	 //MenuGui menugui = new MenuGui();
	 //setVisible(false);
	 
	 }
	 else {
		 status.setText("Incorrect Username or Password");
	 }
 }
 public void lineReader(){
	 Process(5);
	 
 }


public static void Process(int number)
{
try{
 FileReader file1 = new FileReader("carlos.txt");
 BufferedReader f = new BufferedReader(file1);
 String temp;
 int i =0 ;
 while((temp=f.readLine())!=null)
 {
     i++;

     if(i==5)
     {
    	 
    	 miniStatementScreen.setText(temp);
     }


 }
}

catch(Exception e)
{}

}
 
	
 public static void main(String args[]){
	 TextFileTest gui = new TextFileTest();		
		
		}
	
}

and the text file im reading from looks like this:

carlos
12345
000001
250000
Date,Withdraw/Deposit,Amount,Current Balance
10/2/11,Withdraw,100,260000
11/2/11,Withdraw,500,259500
15/2/11,Deposit,1000,260500
22/2/11,Withdraw,5000,255500
24/2/11,Withdraw,5500,250000

What I want to do is, once i enter the correct data into the two textboxes created in the GUI, the user presses the login button and if the data is correct, it will go into the text file, read a specific line then output it into another textbox to displaying that data. Not sure what I am doing wrong.

First of all just for testing purposes take off these functions and put the source code in the button event area. Once you have done that try to print out the output using System.out.println("text"); then change it to your textfield. Because this will help you to understand the problem with the code. Honestly speaking, if I am not missing something, your code is fine. Check if the file is in right location.

I've finally got it to work but when it prints out the contents of the file, it shows as carlos/
how do I get rid of the /? because when I add this code to my main program, I dont want the / to be in the string variable since im comparing strings.

Finally, how would i go about getting to the last line and then just reading the last 5 lines of that text file.
Thanks for all the help.

since i cant edit my post, I've already figured out the / problem. Thanks for the help Software guy.
the only thing i need help on now is to obtain the last 5 lines of a text file without knowing what number that last line will have. Ill keep working at it to find the answer but if someone could tell me what I should look into to solve this would be excellent.

What I can suggest is , read the file, count the number of lines and then close the file, and open the file and read till or after the number you want. But I am afraid it is very inefficient. If your application allows this then I dont see a problem, However if you want fast processing then you have to come up with an idea..

Ok, thanks for all the help. I think I've figured out a way but Ill keep trying.

It looks to me like you could just loop until you have read the line

Date,Withdraw/Deposit,Amount,Current Balance

and then set a boolean flag that all lines after that one are kept.

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.