Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Read line from text file into an array 1

Status
Not open for further replies.

adrianjohnson

Programmer
May 16, 2002
145
GB
I'm fairly new to Java, and looked on the net, but the read from file code I've seen do nothing with the input. What I'd like to do is read a line from a text file, pop it in an array, and then process it later on.

The code I've done is:

String record = null;
int recCount = 0;
int noRec = 0;

// Get the number of lines to process, so the array can be built.
// Is there a better way of doing this?
try
{
FileReader fr = new FileReader("rem.txt");
BufferedReader br = new BufferedReader(fr);

record = new String();
while ((record = br.readLine()) != null)
{
recCount++;
}
}
catch (IOException e)
{
// catch possible io errors from readLine()
System.out.println("Error reading from the file!");
e.printStackTrace();
}

// Create array based on number of lines in text file.
noRec = recCount;
String[] remLine = new String[noRec];

// Read each line, and add to array.
try
{
FileReader fr2 = new FileReader("rem.txt");
BufferedReader br2 = new BufferedReader(fr2);

recCount = 0;
noRec = 0;
while ((remLine[noRec] = br2.readLine()) != null)
{
System.out.println(recCount + ": " + remLine[noRec]);
recCount++;
}
}
catch (IOException e)
{
// catch possible io errors from readLine()
System.out.println("Error reading from the file!");
e.printStackTrace();
}

// This line not working properly, as it returns null.
System.out.println(remLine[noRec]);

// How do I process what's in remLine here????


Thanks,

Adrian Johnson

Adrian Johnson
Assystance - i.t. solutions
 
I think you are going around this in a bit of a daft way ... you really shouldn't read the files twice just to see how many lines there are ...

Code:
ArrayList al = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader("C:/ll_output"));
String line = "";
while ((line = br.readLine()) != null) {
  al.add(line);
}

Object[] array = al.toArray();
 
This will be something like this ......

Greetings [dazed]

/*
* Created on 21-mei-2004
*
*/


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;


public class ReadingFile {
public ReadingFile(String tempFile) throws IOException{

File f = new File(tempFile);
ArrayList al = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
while ((line = br.readLine()) != null) {
al.add(line);
}

Object[] array = al.toArray();

System.out.println("Object:");
for (int count = 0; count < array.length; count++)
System.out.println(array[count]);

}

public static void main(String args[]) throws IOException
{
ReadingFile rfObj = new ReadingFile("Rem.txt");
}

}
 
javaken :

Is this not what I posted ??!!!
 
Your code/solution was very nice Sedj!!!!!!

I complete it because it was so nice ! It's above so short.

Thanks Sedj!!!!

[bigsmile]

 
Sorry for the dense question, but as I said "I'm fairly new to Java"!!

Anyway, is there a declaration I need for ArrayList, as I'm getting an error saying it cannot be resolved or is not a type.

Adrian Johnson
Assystance - i.t. solutions
 
As javaken's version points out in the "import" statements, ArrayList is in the package "java.util" ...
 
I'm getting an error on the while loop:

"Syntax error on keyword "while"; "boolean", "void", "byte", "short", "int", "long", "char", "float", "double", "Identifier", "interface", "class" expected"

Mean anything??


Adrian Johnson
Assystance - i.t. solutions
 
post the exact code ... the examples I and javaken have posted work ok ...
 
This is the complete code. Loads of other stuff, to do with frames etc., but at least you'll see what I'm doing with it.

Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Breaktime extends JMenuBar
{
	String[] fileItems = new String[] { "Exit" };
	String[] remItems = new String[] { "Administer" };
	String[] helpItems = new String [] { "About..."	};
	char[] fileShortcuts = { 'X' };
	char[] remShortcuts = { 'A'	};
	char[] helpShortcuts = { 'B' };
	
	
	public Breaktime()
	{
		
		JMenu fileMenu = new JMenu("File");
		JMenu remMenu = new JMenu("Reminder");
		JMenu helpMenu = new JMenu("Help");
		
		// Assemble the File menu.
		ActionListener printListener = new ActionListener()
		{
			public void actionPerformed(ActionEvent event)
			{
				System.out.println("Menu item pressed.");		
			}
		};
		
		for (int i=0; i<fileItems.length;i++)
		{
			JMenuItem item = new JMenuItem(fileItems[i], fileShortcuts[i]);
			item.setAccelerator(KeyStroke.getKeyStroke(fileShortcuts[i],Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),false));
			item.addActionListener(printListener);
			fileMenu.add(item);
		}
		
		// Assemble the Reminder menu.
		for (int i=0; i<remItems.length; i++)
		{
			JMenuItem item = new JMenuItem(remItems[i]);
			item.setAccelerator(KeyStroke.getKeyStroke(remShortcuts[i],Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),false));
			item.addActionListener(printListener);
			remMenu.add(item);
		}
		
		// Assemble the Reminder menu.
		for (int i=0; i<helpItems.length; i++)
		{
			JMenuItem item = new JMenuItem(helpItems[i]);
			item.setAccelerator(KeyStroke.getKeyStroke(helpShortcuts[i],Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),false));
			item.addActionListener(printListener);
			helpMenu.add(item);
		}
		
		// Add the menus to the menu bar.
		add(fileMenu);
		add(remMenu);
		add(helpMenu);
	}
	
	public void actionPerformed(ActionEvent event)
	{
		//dispose();
		System.exit(0);
	}
	
	
	public static void main(String[] args)
	{
		Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
		int x = (screen.width-400)/2;
		int y = (screen.height-300)/2;
		
		SplashScreen splash = new SplashScreen(3000);
		splash.showSplash();
				
		JFrame frame = new JFrame("Breaktime - reminders program.");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setJMenuBar(new Breaktime());
		frame.pack();
		frame.setBounds(x,y,400,300);
		
		Toolkit tk = Toolkit.getDefaultToolkit();
		Image img = tk.getImage("icon.gif");
		frame.setIconImage(img);
		
		frame.setVisible(true);
		frame.setState ( Frame.ICONIFIED );
		
		ImageIcon icon = new ImageIcon("title.png");
		JLabel l = new JLabel(icon);
		l.setBounds(0,0,icon.getIconWidth(), icon.getIconHeight());
		frame.add(l);
		
		/*
		File f = new File("rem.arf");
		ArrayList al = new ArrayList();
		BufferedReader br = new BufferedReader(new FileReader(f));
		String line = "";
		while ((line = br.readLine()) != null)
		{
			al.add(line);
		}

		Object[] array = al.toArray();
    
		System.out.println("Object:");
		for (int count = 0; count < array.length; count++)
			System.out.println(array[count]);
*/
		

	}

}
 
compiles fine for me ... are you using javac to compile it ?
 
No, Eclipse. You'll need to un-comment your code though (unless you did that and it worked!). I commented it out to test something else, and forgot to uncomment it.


Adrian Johnson
Assystance - i.t. solutions
 
OK, uncommented code, but still cannot find any real problem - apart from :

This :
frame..add(l);
should be :
frame.getContentPane().add(l);

Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Breaktime extends JMenuBar
{
    String[] fileItems = new String[] { "Exit" };
    String[] remItems = new String[] { "Administer" };
    String[] helpItems = new String [] { "About..."    };
    char[] fileShortcuts = { 'X' };
    char[] remShortcuts = { 'A'    };
    char[] helpShortcuts = { 'B' };
    
    
    public Breaktime()
    {
        
        JMenu fileMenu = new JMenu("File");
        JMenu remMenu = new JMenu("Reminder");
        JMenu helpMenu = new JMenu("Help");
        
        // Assemble the File menu.
        ActionListener printListener = new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                System.out.println("Menu item pressed.");        
            }
        };
        
        for (int i=0; i<fileItems.length;i++)
        {
            JMenuItem item = new JMenuItem(fileItems[i], fileShortcuts[i]);
            item.setAccelerator(KeyStroke.getKeyStroke(fileShortcuts[i],Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),false));
            item.addActionListener(printListener);
            fileMenu.add(item);
        }
        
        // Assemble the Reminder menu.
        for (int i=0; i<remItems.length; i++)
        {
            JMenuItem item = new JMenuItem(remItems[i]);
            item.setAccelerator(KeyStroke.getKeyStroke(remShortcuts[i],Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),false));
            item.addActionListener(printListener);
            remMenu.add(item);
        }
        
        // Assemble the Reminder menu.
        for (int i=0; i<helpItems.length; i++)
        {
            JMenuItem item = new JMenuItem(helpItems[i]);
            item.setAccelerator(KeyStroke.getKeyStroke(helpShortcuts[i],Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),false));
            item.addActionListener(printListener);
            helpMenu.add(item);
        }
        
        // Add the menus to the menu bar.
        add(fileMenu);
        add(remMenu);
        add(helpMenu);
    }
    
    public void actionPerformed(ActionEvent event)
    {
        //dispose();
        System.exit(0);
    }
    
    
    public static void main(String[] args)
    {
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (screen.width-400)/2;
        int y = (screen.height-300)/2;
        
        SplashScreen splash = new SplashScreen(3000);
       splash.showSplash();
                
        JFrame frame = new JFrame("Breaktime - reminders program.");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setJMenuBar(new Breaktime());
        frame.pack();
        frame.setBounds(x,y,400,300);
        
        Toolkit tk = Toolkit.getDefaultToolkit();
        Image img = tk.getImage("icon.gif");
        frame.setIconImage(img);
        
        frame.setVisible(true);
        frame.setState ( Frame.ICONIFIED );
        
        ImageIcon icon = new ImageIcon("title.png");
        JLabel l = new JLabel(icon);
        l.setBounds(0,0,icon.getIconWidth(), icon.getIconHeight());
        frame.getContentPane().add(l);
        
        
        File f = new File("rem.arf");
        ArrayList al = new ArrayList();
  	try {
        	BufferedReader br = new BufferedReader(new FileReader(f));
        	String line = "";
        	while ((line = br.readLine()) != null) {
            		al.add(line);	
		}
	} catch (IOException ioe) {
		ioe.printStackTrace(System.err);
	}

        Object[] array = al.toArray();
    
        System.out.println("Object:");
        for (int count = 0; count < array.length; count++)
            System.out.println(array[count]);

        

    }

}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top