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();

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

  • 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.

  • 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

  • Reading in integers from a text file

    Hi, I am going to go for the 'reading in from a text file' action as I haven't done this before. So I have been looking at all the examples and am trying the one out below :) My question is that though the structure seems pretty straightforward, what is the action of the 'token' and why doesn't java recognise it as it is used in many different examples that I have seen?
    public static int[] getIntegersFromFile(String fileName) throws IOException {
                   StringWriter writer = new StringWriter();
                   BufferedReader reader = new BufferedReader(new FileReader(fileName));
                   List<Integer> list = new ArrayList<Integer>();
                   for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                   writer.write(line + " ");
                   StringTokenizer tokens = new StringTokenizer(writertoString());
                   while (tokens.hasMoreTokens()) {
                        String str = tokens.nextToken();
                        try {
                             list.add(new Integer(str));
                             } catch (NumberFormatException e) {
                                  System.out.println("Error '" + str + "' is not an integer.");
                   int[] array = new int[list.size()];
                        for( int i = 0; i < array.length; i++){
                        array[i] = list.get(i);
                   return array;
         }

    Hey, first of all, a piece of advice, try formatting your codes you make easier
    to understand for the people who help you. You can check out the
    formatting tips
    Now, A think that could help you a lot, is the next link, seek out the
    documentation for the StringTokenizer class
    http://java.sun.com/j2se/1.5.0/docs/api/
    Here your code formated and later my interpretation of your question.
    public static int[] getIntegersFromFile(String fileName) throws IOException {
       StringWriter writer = new StringWriter();
       BufferedReader reader = new BufferedReader(new FileReader(fileName));
       List<Integer> list = new ArrayList<Integer>();
       for (String line = reader.readLine(); line != null; line = reader.readLine()) {
          writer.write(line + " ");
       StringTokenizer tokens = new StringTokenizer(writertoString());
       while (tokens.hasMoreTokens()) {
          String str = tokens.nextToken();
          try {
             list.add(new Integer(str));
          } catch (NumberFormatException e) {
             System.out.println("Error '" + str + "' is not an integer.");
       int[] array = new int[list.size()];
       for( int i = 0; i < array.length; i++){
          array = list.get(i);
       return array;
    }StringTokenizer separates the string contained by the space character, and
    each piece of the separated string is stored into the token.
    Further on, could you extend your question about "why doesn't Java
    recognize what?" please, because I don't know if you have a problem
    iterating or is just that it doesn't compile or what.
    Expecting your answer, to complete mine, cya around.
    -Best Regards.

  • 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.

  • Reading and Writing from a text file at the same time

    I know who to use the Scanner and PrintWriter to read from and write to a .txt file. But these are limited. How can I read and write at the same time? Such as open a file and change every third character or change every second word to something else and then write it back. I found this [http://java.sun.com/docs/books/tutorial/essential/io/|http://java.sun.com/docs/books/tutorial/essential/io/] but its a little over my head. Is this the only way to do it?

    wrote:
    You are using buffered reads and writes I would assume, right? Also, how do you think most programs handle this sort of thing? I don't believe I'm using buffering.
    My code looks something like this
    //...necessary imports
    //then
    Scanner inFile = new Scanner (new file("filename1.txt"));
    PrintWriter outFile = new PrintWriter ("filename2.txt");
    //then stuff like
    int x = inFile.hasNextInt();
    outFile.println(x);
    camickr wrote:If you are changing the data "in place", that is none of the data in the file is shifted, then you can use a RandomAccessFile.
    Otherwise, you've been given the answer above.What is RandomAccessFile? Is it what I have a link to? Basically what I do is I write a bunch of numbers to a txt file and then change the numbers I don't need anymore to 0. So say I had 0 1 2 3 4 5 6 7 etc. I would like to to open the txt file and change every second one to 0 so then I'd have only odd numbers and 0s.
    I looked at the documentation for RandomAccessFile and it seems like it might be what I need.
    Thankyou both for your help so far. I took a java course in high school and they only taught me one way to get data from text files and that is what I just showed you. So maybe this questions are really stupid. lol
    Edited by: qw3n on Jun 13, 2009 7:46 PM

  • 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.

  • 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

  • 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?

  • 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 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