Reading a TXT file inton an array - java

Associate
Joined
20 Jun 2004
Posts
988
Location
Manchester
Hi, i've got a textfile named words.txt i want to read into an array, have you any idea how i can do this, because the notes i was given are totally unclear and its driving me insane.
 
Si MPS said:
Hi, i've got a textfile named words.txt i want to read into an array, have you any idea how i can do this, because the notes i was given are totally unclear and its driving me insane.

Perhaps you'd like to show us what you've written so far, and tell us which parts of your code arent working?
 
The words are all on seperate lines, no delimiters.

Code:
package testbufferedreader;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

class TestBufferedReader extends JFrame{

	private JTextArea j = new JTextArea();
	private Container c;
	public TestBufferedReader() {
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				dispose();
				System.exit(0);
			}
		});
		// 
		c = getContentPane();
		// add the only control to the content pane
		c.add(j);
	}

    public void readFile() throws IOException {
    	// Open the file
	File inFile     = new File("c:\\limerick.txt");
    	// Create a file stream, wrapping the file
    	FileReader fileReader = new FileReader(inFile);
    	// Create a second wrapper,
    	BufferedReader bufReader  = new BufferedReader(fileReader);
    	// Read in the first line...
    	String s;
    	// Tries to read forever
    	while (true) {
    		s = bufReader.readLine();
    		// a null reference is returned if the end of file 
    	   	// has been reached.  
    	   	if(s == null) throw new EOFException("Hello");
           		// Add the new string to the text area
           		j.append(s);
           		j.append("\n");  // Append a new line to make it look nice
	}
    }


	public static void main(String args[])  {
		System.out.println("Starting TestBufferedReader...");
		TestBufferedReader mainFrame = new TestBufferedReader();
		mainFrame.setSize(400, 400);
		mainFrame.setTitle("TestBufferedReader");
		mainFrame.setVisible(true);
		// Lets add error detection
		try {
		  mainFrame.readFile();
		}
      	catch (FileNotFoundException e) {
			System.out.println("Warning, FileNotFound exception raised"+e);
		}
		catch (IOException e) {
			System.out.println("Warning, I/O exception "+e);
		}
	}
}

This is my code for reading it into a string, to modify this for an array should i put a 'for loop' in and increment the index until ive filled it with the words?
 
j.append(s); // What this does is to take the string s and put it in the Object j (being the text area here).

so instead of this, you can put it in the array.

static String[] myarray = new array[10]; //declare this as global

and then you put the strings into it by myarray; were i is incremented in a loop.
 
Last edited:
Si MPS said:
This is my code for reading it into a string, to modify this for an array should i put a 'for loop' in and increment the index until ive filled it with the words?

Read up on java collections. There are plenty of types that will allow you to put your Strings into them.
 
drak3 said:
j.append(s); // What this does is to take the string s and put it in the Object j (being the text area here).

so instead of this, you can put it in the array.

static String[] myarray = new array[10]; //declare this as global

and then you put the strings into it by myarray; were i is incremented in a loop.


And how does one know in advance that you have 10 strings?
 
You dont, 10 there is an example. (my bad not excplicitly saying it is example)

You use dynamic data structures in this cases, but before we move into that is best to understand by keeping the rest as simple as possible I belive.
 
Last edited:
drak3 said:
You dont, 10 there is an example. (my bad not excplicitly saying it is example)

You use dynamic data structures in this cases, but before we move into that is best to understand by keeping the rest as simple as possible I belive.

I utterly disagree. IN a modern language like Java there is rarely any need to use fixed sized arrays, and it certainly should never be ones first choice.

We've had decades of security problems because of buffer overrun exploits - reading unchecked data from an external source when you dont know the size of that source and then putting it into a fixed sized array is a bug waiting to happen.
 
Beaut, got it working, reading into an ArrayList

One other thing, does anyone know an easy way to limit the input of a JTextField, i.e. only put 9 characters in
 
Code:
        //Buffered Reader to read from the specified file (fileName)
        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        //String to temporarily hold each line of the file
        String in = reader.readLine();
        //Output String
        String out = "";
        //Stop reading if the line is blank
        while (in != null) {
            //Append output string with next input line (or you could add it to an array or whatever)
            out += in + "\n";
            //Read next line of file
            in = reader.readLine();
        }

edit: seems I was a bit slow there :p
 
Si MPS said:
Beaut, got it working, reading into an ArrayList

One other thing, does anyone know an easy way to limit the input of a JTextField, i.e. only put 9 characters in

Code:
JTextField field = new JTextField();
field.setColumns(9);

I'm not sure if that will actually limit the number of characters you can input or just set the size though.
 
Another question :D
Code:
  if(evt.getSource()==CreateRandomLetters) {
                                 RandomLetterField = ""; //set initial word to blank
     for (int i=1; i<10; i++ ){ // run code 9 times to generate each letter
        number = Math.random(); // random number 
        numericvalue = (number * 26 + 'a'); //get numeric representation of character
        randomChar = (char) numericvalue;    //convert that number into the character
        RandomLetterField = RandomLetterField + randomChar; //add previous character to word
    }
    RandomLetters.setText(RandomLetterField);

this is my code to generate 9 random characters. anyway, what i wish to know is how can i change it to generate uppercase characters instead?

is there any method i can apply to RandomLetters to switch to all uppercase?
 
Back
Top Bottom