Reading in an array from a text file

I'm trying to use a text file to load in some configuratin
data (using actionscript 3) I have it working ok for simple stuff
like gamename=Chess&gamescore=100 , etc... but some of the data
needs to be in an array. Can someone please point me in the right
direction to how I can read in an array from a text file?
Thanks!

the easiest way is to create a string with the (soon-to-be)
array elements separated by a delimiter (like a double comma). read
in your string, then use the split() method of strings to split
your string into an array.

Similar Messages

  • Reading a Random Line from a Text File

    Hello,
    I have a program that reads from a text file words. I currently have a text file around 800KB of words. The problem is, if I try to load this into an arraylist so I can use it in my application, it takes wayy long to load. I was wondering if there was a way to just read a random line from the text file.
    Here is my code, and the text file that the program reads from is called 'wordFile'
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class WordColor extends JFrame{
         public WordColor(){
              super("WordColor");
              setSize(1000,500);
              setVisible(true);
              add(new WordPanel());
         public static void main(String[]r){
              JFrame f = new WordColor();
    class WordPanel extends JPanel implements KeyListener{
         private Graphics2D pane;
         private Image img;
         private char[]characterList;
         private CharacterPosition[]positions;
         private int charcounter = 0;
         private String initialWord;
         private File wordFile = new File("C:\\Documents and Settings\\My Documents\\Java\\projects\\WordColorWords.txt");
         private FontMetrics fm;
         private javax.swing.Timer timer;
         public final static int START = 20;
         public final static int delay = 10;
         public final static int BOTTOMLINE = 375;
         public final static int buffer = 15;
         public final static int distance = 4;
         public final static Color[] colors = new Color[]{Color.red,Color.blue,Color.green,Color.yellow,Color.cyan,
                                                                          Color.magenta,Color.orange,Color.pink};
         public static String[] words;
         public static int descent;
         public static int YAXIS = 75;
         public static int SIZE = 72;
         public WordPanel(){
              words = readWords();
              setLayout(new BorderLayout());
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              setFocusable(true);
              addKeyListener(this);
              timer = new javax.swing.Timer(delay,new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        YAXIS += 1;
                        drawWords();
                        if (YAXIS + descent - buffer >= BOTTOMLINE) lose();
                        if (allColorsOn()) win();
         public void paintComponent(Graphics g){
              super.paintComponent(g);
              if (img == null){
                   img = createImage(getWidth(),getHeight());
                   pane = (Graphics2D)img.getGraphics();
                   pane.setColor(Color.white);
                   pane.fillRect(0,0,getWidth(),getHeight());
                   pane.setFont(new Font("Arial",Font.BOLD,SIZE));
                   pane.setColor(Color.black);
                   drawThickLine(pane,getWidth(),5);
                   fm = g.getFontMetrics(new Font("Arial",Font.BOLD,SIZE));
                   descent = fm.getDescent();
                   distributePositions();
                   drawWords();
                   timer.start();
              g.drawImage(img,0,0,this);
         private void distributePositions(){
              int xaxis = START;
              positions = new CharacterPosition[characterList.length];
              int counter = 0;
              for (char c: characterList){
                   CharacterPosition cp = new CharacterPosition(c,xaxis, Color.black);
                   positions[counter] = cp;
                   counter++;
                   xaxis += fm.charWidth(c)+distance;
         private void drawThickLine(Graphics2D pane, int width, int thickness){
              pane.setColor(Color.black);
              for (int j = BOTTOMLINE;j<BOTTOMLINE+1+thickness;j++){
                   pane.drawLine(0,j,width,j);
         private void drawWords(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              drawThickLine(pane,getWidth(),5);
              for (CharacterPosition cp: positions){
                   int x = cp.getX();
                   char print = cp.getChar();
                   pane.setColor(cp.getColor());
                   pane.drawString(""+print,x,YAXIS);
              repaint();
         private boolean allColorsOn(){
              for (CharacterPosition cp: positions){
                   if (cp.getColor() == Color.black) return false;
              return true;
         private Color randomColor(){
              int rand = (int)(Math.random()*colors.length);
              return colors[rand];
         private void restart(){
              charcounter = 0;
              for (CharacterPosition cp: positions){
                   cp.setColor(Color.black);
         private void win(){
              timer.stop();
              newWord();
         private void newWord(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              repaint();
              drawThickLine(pane,getWidth(),5);
              YAXIS = 75;
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              distributePositions();
              charcounter = 0;
              drawWords();
              timer.start();
         private void lose(){
              timer.stop();
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              pane.setColor(Color.red);
              pane.drawString("Sorry, You Lose!",50,150);
              repaint();
              removeKeyListener(this);
              final JPanel p1 = new JPanel();
              JButton again = new JButton("Play Again?");
              p1.add(again);
              add(p1,"South");
              p1.setBackground(Color.white);
              validate();
              again.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        remove(p1);
                        addKeyListener(WordPanel.this);
                        newWord();
         private String getWord(){
              int rand = (int)(Math.random()*words.length);
              return words[rand];
         private String[] readWords(){
              ArrayList<String> arr = new ArrayList<String>();
              try{
                   BufferedReader buff = new BufferedReader(new FileReader(wordFile));
                   try{
                        String line = null;
                        while (( line = buff.readLine()) != null){
                             line = line.toUpperCase();
                             arr.add(line);
                   finally{
                        buff.close();
              catch(Exception e){e.printStackTrace();}
              Object[] objects = arr.toArray();
              String[] words = new String[objects.length];
              int count = 0;
              for (Object o: objects){
                   words[count] = (String)o;
                   count++;
              return words;
         public void keyPressed(KeyEvent evt){
              char tempchar = evt.getKeyChar();
              String character = ""+tempchar;
              if (character.equalsIgnoreCase(""+positions[charcounter].getChar())){
                   positions[charcounter].setColor(randomColor());
                   charcounter++;
              else if (evt.isShiftDown()){
                   evt.consume();
              else{
                   restart();
              drawWords();
         public void keyTyped(KeyEvent evt){}
         public void keyReleased(KeyEvent evt){}
    class CharacterPosition{
         private int xaxis;
         private char character;
         private Color color;
         public CharacterPosition(char c, int x, Color col){
              xaxis = x;
              character = c;
              color = col;
         public int getX(){
              return xaxis;
         public char getChar(){
              return character;
         public Color getColor(){
              return color;
         public void setColor(Color c){
              color = c;
    }

    I thought that maybe serializing the ArrayList might be faster than creating the ArrayList by iterating over each line in the text file. But alas, I was wrong. Here's my code anyway:
    class WordList extends ArrayList<String>{
      long updated;
    WordList readWordList(File file) throws Exception{
      WordList list = new WordList();
      BufferedReader in = new BufferedReader(new FileReader(file));
      String line = null;
      while ((line = in.readLine()) != null){
        list.add(line);
      in.close();
      list.updated = file.lastModified();
      return list;
    WordList wordList;
    File datFile = new File("words.dat");
    File txtFile = new File("input.txt");
    if (datFile.exists()){
      ObjectInputStream input = new ObjectInputStream(new FileInputStream(datFile));
      wordList = (WordList)input.readObject();
      if (wordList.updated < txtFile.lastModified()){
        //if the text file has been updated, re-read it
        wordList = readWordList(txtFile);
        ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
        output.writeObject(wordList);
        output.close();
    } else {
      //serialized list does not exist--create it
      wordList = readWordList(txtFile);
      ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
      output.writeObject(wordList);
      output.close();
    }The text file contained one random sequence of letters per line. For example:
    hwnuu
    nhpgaucah
    zfbylzt
    hwnc
    gicgwkhStats:
    Text file size: 892K
    Serialized file size: 1.1MB
    Time to read from text file: 795ms
    Time to read from serialized file: 1216ms

  • How can I read a specific character from a text file?

    Hi All!
    I would like to read a specific character from a text file, e.g. the 2012th character in a text file with 7034 characters.
    How can I do this?
    Thanks
    Johannes

    just use the skip(long) method of the input stream that reads the text file and skip over the desired number of bytes

  • Retrieving  two dimensional arrays from a text file.

    Good evening
    I am having a problem with reading a text file, and putting this info into a 2D array to be put into a table.
    I have the table already(but no code to add rows to the table incase the array increases)
    The array is called Product[a][ b ]
    where a is the product number(the row), and b are details about this product.
    The file i want to be read looks like this:
    data.txt
    CPU|AMD|X2, 64bit, 2GHz|$150|9
    Video card|NVidia|7800 GTX 256MB|$400|4
    e.g. product[2][4] would equal 4
    Basically: Type, manufacturer, specifications, price, amount in stock.
    the "splitter" or "field terminator" is "|"
    This is what i want it to do:
    Store fileline into single string,
    split string and put it in product[ j ][ i ]
    repeat with next lines until nothing is read anymore.
    This is the code I have so far:
    try{
            FileReader textFileReader = new FileReader("C://BACKUP2//data.txt");
            BufferedReader textReader = new BufferedReader(textFileReader);
            for(int j=0; j<0; j++){
                 for(int i=0; i<6; i++){ //i starts at 0, condition: i is under 6, 1 is added to i at each loop/update.             
                       ProductT = textReader.readLine();
                       textReader.close();
                       for(String Product[j] : ProductT.split("|")){ //this line is completly wrong, but i don't know how else to do it.
         // for counting for the number of columns
    catch (IOException e) {System.out.println(e);}
    I don't even think this code makes any bloody sense, I don't know if I'm approaching it correctly.
    Would anyone be gracious enough to give me a helping hand and tell me what/how to change my code?
    from what I see, the problem lies less in the loops, but more in the splitting of the string. no function seems to like 2D arrays :(

    So this is where I stand:
         //Reading
        try{
            FileReader textFileReader = new FileReader("C://BACKUP2//data.txt");
            BufferedReader textReader = new BufferedReader(textFileReader);
            for(int j=0; j>0; j++){ // this will go on forever now or what?
    // yes, this will loop forever, which is fine as long as you break out of the loop when you reach the end of the file (which is indicated by textReader.readLine() returning null)
                 // replace the for(String currentField : ProductT.split("|")) loop with this one
                 //for(int i=0; i<6; i++){ //i starts at 0, condition: i is under 6, 1 is added to i at update.       
                      String inputline = textReader.readLine();    // read a single line from the file each time through the loop
                      //while (inputline != null) {
                            if (inputline != null) {    // check if the end of the file has been reached
                           //ProductT = textReader.readLine(); //put to single string
                       //textReader.close(); //shut it off    // move this line to the end of processing, you don't want to close the file until you've read everything from it.
                       //for(String currentField : ProductT.split("|")){   //Split string...      according to JBuilder "The local variable currentField is never read"
                             // switch this loop to use the regular for(  ;  ;  ) type, that way you will have another counter to use as the second index in the product assignment
                                         //currentField = Product[j];
                        product[i][] = currentField; // use the index of the second loop as the second index here
    else {
    break; // break out of the loop when end of file is reached
         //} // the for i etc. end here
    } // End for j et cetera...
         } //end Try
    catch (IOException e) {System.out.println(e);}
    //cut the crap
    // close the reader here
    ok - so I am not quite sure about what you mean here
    "Assign each of the 5 fields to the five [][j]
    positions of the array. "
    should i put 5 "fors" in there? - currently the
    program is compiling - although they do not appear in
    the table.I put comments in the code that should answer those questions.
    The code for the table is
    Object[][] data = {
              {Product[0][0], Product[0][1],
                   Product[0][2], Product[0][3], Product[0][4]},
                   {Product[1][0], Product[1][1],
    Product[1][2], Product[1][3],
    uct[1][3], Product[1][4]},
                          {Product[2][0], Product[2][1],
    Product[2][2], Product[2][3],
    ct[2][3], Product[2][4]},
                              {Product[3][0], Product[3][1],
    Product[3][2],
    Product[3][2], Product[3][3], Product[3][4]},
                    {Product[4][0], Product[4][1],
    Product[4][2],
    Product[4][2], Product[4][3], Product[4][4]},
    ;If I do not declare any of these strings (e.g. I have
    only declared Product[0-2][] oldschol style) an error
    occurs, telling me that
    Caused by:
    java.lang.ArrayIndexOutOfBoundsException: 3
         at data.<init>(data.java:112)
         ... 5 more
    When you declare product, you'll need to give it a size for both dimensions. The first dimension will be the number of lines to be read from the file. You'll need to know this before allocating the array, so either count them in the file, (if that's good enough for this assignment) or loop through the file once before reading it to count the lines. The second dimension of the array will be 5, since that's how many fields each line has.
    btw; do I give those duke stars when all problems of
    my life(currently: reading the two dimensional
    string) have been resolved?I don't know about [i]all the problems of your life, but when the topic of the thread has been solved, then give them to whoever helped. :)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Reading strings and integers from a text file

    I want to read the contents of a text file and print them to screen, but am having problems reading integers. The file contains employee's personal info and basically looks like this:
    Warren Laing
    32 //age, data type is int
    M //gender, data type is String
    Sharon Smith
    44
    F
    Here's what I've done so far. The method should continue reading the file until there's no lines left. When I call it from main, I get a numberFormatException error. I'm not sure why because the data types of the set and get methods are correct, the right packages have been imported, and I'm sure I've used Integer.parseInt() correctly (if not, pls let me know). Can anyone suggest why I'm getting errors, or where my code is going wrong?
    many thanks
    Chris
    public void readFile() throws IOException{
    BufferedReader read = new BufferedReader(new FileReader("personal.txt"));
    int age = 0;
    String input = "";
    input = read.readLine();
    while (input != null){
    setName(input);
    age = Integer.parseInt(input);
    setAge(age);
    input = read.readLine();
    setGender(input);
    System.out.println("Name: " + getName() + " Age: " + getAge() + " Gender: " + getGender());
    read.close();

    To answer your question - I'm teaching myself java and I haven't covered enumeration classes yet.
    With the setGender("Q") scenario, the data in the text file has already been validated by other methods before being written to the file. Anyway I worked out my problems were caused by "input = read.readLine()" being in the wrong places. The code below works fine though I've left out the set and get methods for the time being.
    Chris
    public static void readFile()throws IOException{
    String name = "";
    String gender = "";
    int age = 0;
    BufferedReader read = new BufferedReader(new FileReader("myfile.txt"));
    String input = read.readLine();
    while(input != null){
    name = input;
    input = read.readLine();
    gender = input;
    input = read.readLine();
    age = Integer.parseInt(input);
    input = read.readLine();
    System.out.println("Name: " + name + " Gender: " + gender + " Age: " + age);
    read.close();

  • How can i read all the lines from a text file in specific places and use the data ?

    string[] lines = File.ReadAllLines(@"c:\wmiclasses\wmiclasses1.txt");
    for (int i = 0; i < lines.Length; i++)
    if (lines[i].StartsWith("ComboBox"))
    And this is how the text file content look like:
    ComboBox Name cmbxOption
    Classes Win32_1394Controller
    Classes Win32_1394ControllerDevice
    ComboBox Name cmbxStorage
    Classes Win32_LogicalFileSecuritySetting
    Classes Win32_TapeDrive
    What i need to do is some things:
    1. Each time the line start with ComboBox then to get only the ComboBox name from the line for example cmbxOption.
       Since i have already this ComboBoxes in my form1 designer i need to identify where the cmbxOption start and end and when the next ComboBox start cmbxStorage.
    2. To get all the lines of the current ComboBox for example this lines belong to cmbxOption:
    Classes Win32_1394Controller
    Classes Win32_1394ControllerDevice
    3. To create from each line a Key and Value for example from the line:
    Classes Win32_1394Controller
    Then the key will be Win32_1394Controller and the value will be only 1394Controller
    Then the second line key Win32_1394ControllerDevice and value only 1394ControllerDevice
    4. To add to the correct belonging ComboBox only the value 1394Controller.
    5. To make that when i select in the ComboBox for example in cmbxOption the item 1394Controller it will act like i selected Win32_1394Controller.
    For example in this event:
    private void cmbxOption_SelectedIndexChanged(object sender, EventArgs e)
    InsertInfo(cmbxOption.SelectedItem.ToString(), ref lstDisplayHardware, chkHardware.Checked);
    In need that the SelectedItem will be Win32_1394Controller but the user will see in the cmbxOption only 1394Controller without the Win32_
    This is the start of the method InsertInfo
    private void InsertInfo(string Key, ref ListView lst, bool DontInsertNull)
    That's why i need that the Key will be Win32_1394Controller but i want that the user will see in the ComboBox only 1394Controller without the Win32_

    Hello,
    Here is a running start on getting specific lines in the case lines starting with ComboBox. I took your data and placed it into a text file named TextFile1.txt in the bin\debug folder. Code below was done in
    a console app.
    using System;
    using System.IO;
    using System.Linq;
    namespace ConsoleApplication1
    internal class Program
    private static void Main(string[] args)
    var result =
    from T in File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TextFile1.txt"))
    .Select((line, index) => new { Line = line, Index = index })
    .Where((s) => s.Line.StartsWith("ComboBox"))
    select T
    ).ToList();
    if (result.Count > 0)
    foreach (var item in result)
    Console.WriteLine("Line: {0} Data: {1}", item.Index, item.Line);
    Console.ReadLine();
    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my webpage under my profile but do not reply to forum questions.

  • How to read numeric array from a text file

    I'm new to file I/O in LabView. Basically, all I need is to read the attached 2000 x 9 array into an identical 2D array within LabView. I have tried simply using the READ FROM SPREADSHEET FILE VI but it only reads the first column. Any help would be greatly appreciated.
    Thanks, Hunter
    Attachments:
    FRFx1.dat ‏286 KB

    I cant open theother examples, so maybe I`m posting something similar, but here`s my approach in LV 6.1
    First convert all double spaces to single spaces, then all single spaces to tab. Then use "Spreadsheet string to array" cutting out the first column (extra tabs produce an extra column).
    Shane.
    Using LV 6.1 and 8.2.1 on W2k (SP4) and WXP (SP2)
    Attachments:
    Read_in_Matlab_file(6.1).vi ‏26 KB

  • Reading parameters lists from a text file

    Hi All,
    Using CR XI R2 with VB6  and external .rpt files - - - - -
    In a VB6 app I use VB to loop through my tables to create dynamic parameter lists (CR XI is limited to the number of parameters it can create from the table). This works well but each time the user refreshes the report the same code is run to re-create the parameter list which is redundant and slows down the report(s).
    Is it possible to manually create a series of text files - say each morning - and then read the parameter lists from the text file(s) at runtime instead of doing it on the fly each time?
    Thanks in advance!
    Peter Tyler
    Geneva - Switzerland

    I find this sentence confusing:
    Is it possible to manually create a series of text files - say each morning - and then read the parameter lists from the text file(s) at runtime instead of doing it on the fly each time?
    Typically, runtime means on the fly - I think...
    So, I'm not sure if you are trying to read a saved data report and filter that saved data so that you do not have to hit the database(?).
    Creating a text file is beyond the support of this forum, though that should be a trivial exercise. Reading a text file and passing the results to a parameter is the same thing you are doing already, so I'm not sure where the hang up would be here(?)
    Or - rather than creating a text file, why not create a temp table and query it as you do when you loop through the tables to create dynamic parameter lists(?).
    I'm pretty lost here...
    Ludek
    Follow us on Twitter http://twitter.com/SAPCRNetSup
    Got Enhancement ideas? Try the [SAP Idea Place|https://ideas.sap.com/community/products_and_solutions/crystalreports]

  • Reading signed interger from a text file:

    Is this possible with some construct in java? Attempting to read a signed number using .readInt() throws an exception before the first token is a malformed int. i,e, the sign + or -.
    I would like to read a signed integer from a text file but I am clueless.
    Any help is appreciated.

    It can be a bit of a dilemma for lexical analysers. Say you read "a + 12" then you'd generally want to process that as three separate lexemes. The monadic form of plus is less common than the monadic minus.
    A quick test shows that "+12" and "+ 12" are both rejected by Integer.parseInt() (which surprised me).
    I'd suggest if you want to read positive numbers then first analyse your input using a regular expression, for example "\\s*([-+]?)\\s*(\\d+)" followed by
    (matcher.match(1).equals("-") ? -1 : 1) * Integer.parseInt(matcher.match(2));Edited by: malcolmmc on May 24, 2010 2:10 PM

  • Indesign CS3-JS - Problem in reading text from a text file

    Can anyone help me...
    I have an problem with reading text from an txt file. By "readln" methot I can read only the first line of the text, is there any method to read the consecutive lines from the text file.
    Currently I am using Indesign CS3 with Java Script (for PC).
    My Java Script is as follows........
    var myNewLinksFile = myFindFile("/Links/NewLinks.txt")
    var myNewLinks = File(myNewLinksFile);
    var a = myNewLinks.open("r", undefined, undefined);
    myLine = myNewLinks.readln();
    alert(myLine);
    function myFindFile(myFilePath){
    var myScriptFile = myGetScriptPath();
    var myScriptFile = File(myScriptFile);
    var myScriptFolder = myScriptFile.path;
    myFilePath = myScriptFolder + myFilePath;
    if(File(myFilePath).exists == false){
    //Display a dialog.
    myFilePath = File.openDialog("Choose the file containing your find/change list");
    return myFilePath;
    function myGetScriptPath(){
    try{
    myFile = app.activeScript;
    catch(myError){
    myFile = myError.fileName;
    return myFile;
    Thanks,
    Bharath Raja G

    Hi Bharath Raja G,
    If you want to use readln, you'll have to iterate. I don't see a for loop in your example, so you're not iterating. To see how it works, take a closer look at FindChangeByList.jsx--you'll see that that script iterates to read the text file line by line (until it reaches the end of the file).
    Thanks,
    Ole

  • Read specified line from a text file

    Hi,
    I am trying to read a specific line from a text file. I don't want to read all of it but just this specific line... say line number 2. Is there a method built-in in java or should I code this myself?
    Thanks and regards,
    Krt_Malta

    Krt_malta wrote:
    I am trying to read a specific line from a text file. I don't want to read all of it but just this specific line... say line number 2. Is there a method built-in in java or should I code this myself?Is there anything in your use case that precludes using the offset of the start of the line rather than the line number?

  • Reading fields from a text file

    Hi, I'm fairly new to this so bear with me.
    This is for an assignment - the idea is to cretae an online system for booking seats at a cinema - haven't got past the login stage yet?
    I've got an applet that needs to read in a field from a text file.
    I'm using the StringTokenizer function.
    I've put a test in to check that the applet can find the file, which seems to be ok.
    However, it's not reading from the file.
    Te file is a simple text file - fields are seperated by a comma and a space.
    Any ideas?
    Please help as this is quite urgent.
    Prototype Code is below
    public class cinema extends Applet implements ActionListener, ItemListener{
    private List ActionList;
    private int listIndex;
    TextArea t = new TextArea(5, 30);
    private Button gobutton, writebutton, login, logout;
    private PrintWriter suggestfile;
    TextField Userid, password, enterField;
    private int count, checkuser;
    private BufferedReader firstn;
    File myFile = new File("e:\\Ian\\Unistuff\\2nd Year\\se2\\cinema2\\src\\cinema2\\member.txt");
    //Construct the applet
    public cinema() {
    enterField = new TextField("Please enter user ID and Password");
    enterField.setEditable(false);
    add(enterField);
    Userid = new TextField(3);
    add(Userid);
    password = new TextField(10);
    password.setEchoChar('*');
    add(password);
    //Initialize the applet
    public void init() {
    BorderLayout borderLayout1 = new BorderLayout();
    //some code ommitted
    t.setEditable(false);
    add(t);
    gobutton = new Button("Go!");
    add(gobutton);
    gobutton.addActionListener(this);
    public void actionPerformed(ActionEvent event) {
    if (event.getSource() == gobutton) {
    try {
    firstn = new BufferedReader( new FileReader(myFile));
    catch (IOException e) {
    t.setText("Member database missing - please contact Chairperson");
    return;
    try {
    String line1;
    boolean found = false;
    while (( ( line1 = firstn.readLine() ) != null) && (! found))
    {StringTokenizer token1 = new StringTokenizer (line1, " ,");
                              String user = token1.nextToken();
                                 if (Userid.getText().equals(user))
                                   { found = true;
                                     t.setText("Hello");
    firstn.close();
    catch (IOException e) {
    System.err.println("Error Reading File " + myFile + ": " + e.toString());
    Here's the text file:
    Ian, Dodson, 001, rubbish
    Joe, Bloggs, 002, medway
    Bill, Smith, 003, unique
    Guest, , Guest,
    To test that it is working, it should just put a message in the Text Area, but nothing happens when you press the "go" button.

    1. Your applet will not work, because it is trying to
    read file from local disk.
    2. This task can be solved by simple CGI script
    (which is much more common and universal thing than
    java), so you do not need to use java if you want to
    send 3 lines to a server.
    3. See examples and read some books.1. Stated the obvious.
    2. This is a java forum, not Perl.
    3. Pathetic and patronizing.
    Very helpful.

  • Read email adress from a text file then check the validity of them

    a text file has three lines, each line contains one email adress:
    [email protected]
    qwe@@ws.com
    wer//@we.net
    read the email address from a text file, then check which one is invalid, output the invalid email adress in the console.

    no 3 .umm, an email adress can have more than 2 '.'s in it,
    example:
    [email protected]
    would be a valid email address.
    To decide what a valid address is you'd need to parse it against the correct standard.
    I think however that javax.mail.internet.InternetAddress does this for you, check out the docs:
    http://java.sun.com/products/javamail/1.2/docs/javadocs/javax/mail/internet/InternetAddress.html
    even if it parses it may not be a valid address though in that it may not actually exist.

  • I can't read in a date from a txt file

    Im not sure of the code needed to read in a date from the text file, this is an example of the text file:
    1
    2
    2003
    ie,
    day
    month year
    I have to read in this date, this is the set method for the date:
    public void setPurchaseDate (int d, int m, int y)
    new Date(d,m,y);
    And this is the code that I have tried using to readin the date:
      PurchaseDate=(Integer.parseInt(line),Integer.parseInt(line),Integer.parseInt(line));now i know its wrong, I just dont know what the code should be!!
    Cheers

    ok, I am going to go through it and see what values I can and cant read in, here is the code i am trying to use:
    private void addx()
           FileReader fin;
           int noBooks;
           int itemNum;
           String title;
           String subject;
           double costNew;
           double costPaid;
           String isbn;
           double sellingPrice = 0;
           int noAuthors;
           int day;
           int month;
           int year;
            String seperator = "#";
            Book[] book = new Book[9];
            try
                fin = new FileReader("Books.txt");
                BufferedReader buff = new BufferedReader(fin);
                String line = buff.readLine();
                int count= 0;
                //read in Number of books
                noBooks=Integer.parseInt(line);
                while( line != null)
                    //Read in item number
                    itemNum = Integer.parseInt(line);
                    //Read in title
                    title = buff.readLine();
                    //Read in number of authors
                    noAuthors=Integer.parseInt(line);
                    //Read each line in as an author until number of authors reached
                    ArrayList authors = new ArrayList();
                    for(int i=0; i < noAuthors ; i++)
                        authors.add(buff.readLine());
                    //Read in cost new
                    costNew = Double.parseDouble(line);
                    //Read in subject
                    subject = buff.readLine();
                    //Read in ISBN
                    isbn = buff.readLine();              
                    //Read in purchase day
                    day = Integer.parseInt(line);
                    //Read in purchase month
                    month=Integer.parseInt (line);
                    //Read in purchase year
                    year = Integer.parseInt (line);
                    //Read in cost paid
                    costPaid = Double.parseDouble(line);
                    line = buff.readLine();
                    //Pass date, month and year values to array
                    Date purchaseDate =new Date(day,month,year);
                    //Pass values to constructor
                    if (line.equals(seperator))
                        book[count++] = new Book(itemNum, title, authors, subject, purchaseDate,costNew,costPaid,isbn, sellingPrice,noAuthors);
                  // line = buff.readLine();
                System.out.println(book.toString());
            catch(Exception ex)
                System.out.println(ex.toString());
             }

  • Retrieving certain line from a text file

    Hi,
    I would like to know on how to read a specific line from a text file using NetBeans IDE 6.1? Below is the content of my text file and my code.I will appreciate if anyone can help. Thank in advance= D
    Matrix1.text
    <matrix>
    rows = 2
    cols = 2
    1 2
    2 4
    </matrix>
    I would like to retrieve the interger 1,2,2,4.
    MyCode.java
    import java.io.IOException;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    class Matrix {
    double [][] element;
    static void getFile(String fileName) throws IOException{
    int counter = 0;
    BufferedReader br = null;
    try{
    br = new BufferedReader(new FileReader(fileName));
    String line = br.readLine();
    while (line != null){
    line = br.readLine();
    System.out.println(line);
    counter ++;
    System.out.println("Total line : " + counter);
    br.close();
    }catch(FileNotFoundException ex){
    System.out.println(ex.getMessage());
    }

    Wonders wrote:
    Thank for reply=D
    Yap the row and column will change but i had already parse these lines into my code. However, i am still figuring on how to get the integer number 1,2,2,4 of the text file using while loop and not include the "</matrix>" in the reading. Can this be done?If the numbers you want are at fixed byte positions in the file that are known ahead of time, you can use java.io.RandomAccessFile to skip to those positions. However, that seems unlikely.
    If, as is the more likely case, those are not at fixed positions, you'll have to read everything preceding them. (Note that this is not a Java issue. This is how file I/O works.) You'll need to ignore the lines that are meaningless to you (read those lines and do nothing with them) figure out, by whatever rules you have--line numbers, preceding tokens, whatever--when you're at the lines you do care about, and then read and process those lines accordingly.

Maybe you are looking for