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.

Similar Messages

  • Reading one line from a text file into an array

    i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
    public static void readAndProcessData(FileInputStream stream){
         InputStreamReader iStrReader = new InputStreamReader (stream);
         BufferedReader reader = new BufferedReader (iStrReader);
         String line = "";          
         try{
         int i = 0;
              while (line != null){                 
                   names[i] = reader.readLine();
                   score[i] = reader.readLine();
                   line = reader.readLine();
                   i++;                
              }catch (IOException e){
              System.out.println("Error in file access");
    this section calls it:
    try{                         
         FileInputStream stream = new FileInputStream("ISU.txt");
              HighScore.readAndProcessData(stream);
              stream.close();
              names = HighScore.getNames();
              scores = HighScore.getScores();
         }catch(IOException e){
              System.out.println("Error in accessing file." + e.toString());
    it gives me an array index out of bounds error

    oh wait I see it when I looked at the original quote.
    They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens.

  • Reading Each String From a text File

    Hello everyone...,
    I've a doubt in File...cos am not aware of File.....Could anyone
    plz tell me how do i read each String from a text file and store those Strings in each File...For example if a file contains "Java Tchnology forums, File handling in Java"...
    The output should be like this... Each file should contains each String....i.e..., Java-File1,Technology-File2...and so on....Plz anyone help me

    The Java� Tutorials > Essential Classes: Basic I/O

  • How to read every line from a text file???

    How can i read every line from my text file ("eka.txt")
    now it only reads the first line and prints it out.
    What is wrong with this?
    import java.io.*;
    import java.util.*;
    class Testi{
         public static void main(String []args)throws IOException {
         BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
    File inputFile = new File ("eka.txt");
    FileReader fis =new FileReader(inputFile);
    BufferedReader bis = new BufferedReader(fis);
    String test=bis.readLine();
    String tmp= "";
    while((bis.readLine().trim() != null)) {
    int spacefound=0;
    int l=test.indexOf(" ");
         for(int i=0;i<test.length();i++){
         char c=test.charAt(i);
         if(c!=' ') tmp+=""+c;
         if(c==' ' && (spacefound<1) && !(tmp.equals(""))){
         tmp+=""+c;
         spacefound++;
         if(tmp.length()==l) {
         System.out.println(tmp);
         tmp="";
         spacefound=0;
         if(tmp.length()<l){
         for(int i=0;i<=(l-tmp.length());i++)
         tmp+=""+' ';
         System.out.println(tmp);

    Try this code, Hope it servers your purpose.
    import java.io.*;
    import java.util.*;
    class Testi {
         public static void main(String []args)throws IOException {
              BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
              File inputFile = new File ("Eka.txt");
              FileReader fis =new FileReader(inputFile);
              BufferedReader bis = new BufferedReader(fis);
              String test=bis.readLine();
              while(test != null) {
                   StringTokenizer st = new StringTokenizer(test," ");
                   while(st.hasMoreTokens())
                        System.out.println(st.nextToken());
                   test = bis.readLine();
    }Sudha

  • How to read some lines from a text file using java.

    hi,
    i m new to java and i want to read some lines from a text file based on some string occurrence in the file. This file to be read in steps.
    we only want to read the file upto the first Occurrence of "TEXT" string.
    How to do it ,,,
    Kinldy give the code
    Regards,
    Sagar
    this is the text file
    dfgjdjj
    sfjhjkd
    ghjkdg
    hjkdgh TEXT
    ikeyt
    ujt
    jk
    tyk TEXT
    rukl
    r

    Hendawy wrote:
    Since the word "TEXT" is formed of 4 letters, you would read the text file 4 bytes by four bytes. Wrong on two counts. First, the file may not be encoded 1 byte per character. It could be utf-16 in which case it would be two byte per character. Second, even if it were 1 byte per character, the string "Text" may not start on a 4 byte boundary.
    Consider a FileInputStream object "fis" that points to your text file. use fis.read(byte[] array, int offset, int len) to read every four bytes. Convert the "TEXT" String into a byte array "TEXT".getBytes(), and yous the Arrays class to compare the equality of the read bytes with your "TEXT".getBytes()Wrong since it relies on my second point and will fail when fis.read(byte[] array, int offset, int len) does not read 4 bytes (as is no guaranteed to). Check the Javadoc. Also, the file may not be encoded with the default character encoding.
    The problem is easily solved by reading a line at a time using a BufferedReader wrapping an InputStreamReader wrapping a FileInputStream and specifying the correct character encoding.
    Edited by: sabre150 on Apr 29, 2009 2:13 PM

  • How do i read complete line from a text file in j2me?????

    how do i read complete line from a text file in j2me????? I wanna read file line by line not char by char..Even i tried with readUTF of datainputstream to read word by word but i got UTFDataFormatException.. Please solve my problem.. Thanks in advance..

    That is not my problem . i already read it char by char.. i am getting complete line..But this process is taking to much time..So thats why i directly wanna read complete line or word to save time..

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

  • 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

  • How to read some records from a text file into java(not all records)

    hello,
    how to read text files into java. i need only few records from the text file not all records at a time.
    If any one knows plz reply me
    my id is [email protected]

    this snipet reads a text file line by line from line 1 to 3
    try {
                  FileReader fr = new FileReader(directory);
                  BufferedReader br = new BufferedReader(fr);
                  int counter = 0;
                  while ((dbconn = br.readLine()) != null) {
                      switch(counter){
                          case 0:
                            status = dbconn;
                          break;
                          case 1:
                            userName = dbconn;
                          break;
                          case 2:
                            apword = dbconn;
                          break;
                      counter++;
                  br.close();
        }catch(IOException e){
        }

  • At end of tether!  Reading in variables from a text file

    Hi all
    My stress factor has gone through the roof because I am trying to read in from a text file (you may have seen some earlir questions about ArrayLists) it's just not working!
    The code is below. The result is that it's reading in all of the car data, none of the motorbike and only the first line for the services. It's odd and it's driving me insane!
    Here's an example of the data it's reading. There are about 7-10 sets of data per type
    <car><reg>AB04CDE</reg><make>Ford</make><model>Fiesta</model><colour>blue</colour><passenger_no>4</passenger_no></car>
    <service><service_no>13570</service_no><reg>J605PLE</reg><date>15:07:2006</date><miles>20000</miles><part_replaced>brake_pads</part_replaced><part_replaced>front_tyres</part_replaced></service>
    <motorbike><reg>TT05EKJ</reg><make>Triumph</make><model>Speedmaster</model><colour>black</colour><load>20.50</load></motorbike>
    Here's the code
    while (moreToRead) {
            String line;
            try {
              line = fileReader.getNextStructure();
    // collect the data from the file
              if (line.indexOf("<car>")> -1){
                // Select/Extract the registration element
                int nStart = line.indexOf("<reg>");
                int nEnd = line.indexOf("</reg>");
                String reg = line.substring(nStart+5,nEnd);
                // Select/Extract the make element
                nStart = line.indexOf("<make>");
                nEnd = line.indexOf("</make>");
                String make = line.substring(nStart+6,nEnd);
                // Select/Extract the model element
                nStart = line.indexOf("<model>");
                nEnd = line.indexOf("</model>");
                String model = line.substring(nStart+7,nEnd);
                // Select/Extract the colour element
                nStart = line.indexOf("<colour>");
                nEnd = line.indexOf("</colour>");
                String colour = line.substring(nStart+8,nEnd);
                // Select/Extract the passenger_no element
                nStart = line.indexOf("<passenger_no>");
                nEnd = line.indexOf("</passenger_no>");
                String passenger_no = line.substring(nStart+14,nEnd);
                //convert string to int
                int passengerInt = Integer.parseInt(passenger_no);
                // declare new object car and assign the variables then add it to the array.
                Car c = new Car (reg, make, model, colour, passengerInt);
                carList.add(c);
      } else if (line.indexOf("<bike>")> -1) {
             // Select/Extract the registration element
             int nStart = line.indexOf("<reg>");
             int nEnd = line.indexOf("</reg>");
             String reg = line.substring(nStart+5,nEnd);
             // Select/Extract the make element
             nStart = line.indexOf("<make>");
             nEnd = line.indexOf("</make>");
             String make = line.substring(nStart+6,nEnd);
             // Select/Extract the model element
             nStart = line.indexOf("<model>");
             nEnd = line.indexOf("</model>");
             String model = line.substring(nStart+7,nEnd);
             // Select/Extract the colour element
             nStart = line.indexOf("<colour>");
             nEnd = line.indexOf("</colour>");
             String colour = line.substring(nStart+8,nEnd);
             // Select/Extract the load element
             nStart = line.indexOf("<load>");
             nEnd = line.indexOf("</load>");
             String load = line.substring(nStart+6,nEnd);
             //convert load string to double
             double bikeLoad = Double.parseDouble(load);
             // declare new object motorbike and assign the variables then add it to the array.
             Motorbike m = new Motorbike (reg, make, model, colour, bikeLoad);
             bikeList.add(m);
      } else  {
        // Select/Extract the service_number element
        int nStart = line.indexOf("<service_no>");
        int nEnd = line.indexOf("</service_no>");
        String service_no = line.substring(nStart+12,nEnd);
        console.println("service = " + service_no);
        nStart = line.indexOf("<reg>");
        nEnd = line.indexOf("</reg>");
        String reg = line.substring(nStart+5,nEnd);
        console.println("service = " + reg);
        nStart = line.indexOf("<date>");
        nEnd = line.indexOf("</date>");
        String date = line.substring(nStart+6,nEnd);
        console.println("service = " + date);
        nStart = line.indexOf("<miles>");
        nEnd = line.indexOf("</miles>");
        String miles = line.substring(nStart+7,nEnd);
        console.println("service = " + miles);
        nStart = line.indexOf("<part_replaced>");
        nEnd = line.indexOf("</part_replaced>");
        String part_replaced = line.substring(nStart+15,nEnd);
        console.println("service = " + part_replaced);
        //convert string to int
        int dateOfService = Integer.parseInt(date);
        //convert string to double
        double milesAtService = Double.parseDouble(miles);
        //convert service no to unique int
        int serviceNo = Integer.parseInt(service_no);
        // declare new object service and assign the variables then add it to the array.
        Service s = new Service (reg, part_replaced, serviceNo, dateOfService, milesAtService);
          serviceList.add(s);
          catch (Exception e) {
            // Run out of data
            moreToRead = false;
    } If anyone can spy anything that could be causing this I love your advice. I simply can't see it.
    Jo

    hi jos,
    we have been asked not to use a parser for this assignment. evil
    tutor i think! lolYour example seems to imply that all the <tag> ... </tag> pairs have
    to occur on a single line; if that is so, you can do some cheap
    programming like this:String getText(String line, String tag) {
       int start= line.indexOf("<"+tag+">");
       int end= line.indexOf("</"+tag+">", start);
       if (start < 0 || end < 0) return null; // no <tag> ... </tag> pair found
       // return the text in between the <tag> ... </tag> tags
       return line.substring(start+tag.length()+2, end);
    }kind regards,
    Jos

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

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

  • Reading dilimited input from a text file with tokenizer

    i am trying to read in a text file with the following structure: 2 integers on each line with comma as the delimitor.
    i am using the BufferedReader stream and Tokenizer to detect ",".
    try {
    BufferedReader in = new BufferedReader(new FileReader(filename));
    //read in the data file
    while ((s = in.readLine())!= null) {
    int i = 0;
    for (i = 0; i < 100; i++) {
    t = new StringTokenizer(s,",");
    A1 = Integer.parseInt(t.nextToken());
    catch (IOException e) {System.err.println(e);}
    When i print out A1[i], it only reads the last line of the text file. Please tell me what's wrong.
    Also i'd really like A1[i] to store the integer before the comma and another array A2[i] to store the integer after the comma. Please help.
    Thanks.
    p.s. A1 and A2 are arrays...when i previewd message in Netscape 7 it left out the brackets and the index....

    What is the for i loop for? If it is to read the next line from the file, then the while loop has taken care of it. Other than this there should be no problem with the rest of the code.
    Just add another line to store the next token into A2.

  • 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

Maybe you are looking for

  • Retreiving a fat16 or 32 partitions real uuid on snow leopard

    Hello, I do have a big problem. Since on mac at least on snow leopard I'm unable to retreive the real partition UUID from a fat formated fat16 or 32 usb stick. The problem is that this stick is a real official document for work. The stick needs regul

  • How to search table configuration?

    Hi In SE10, we can use the user name and find out the configuration done by the user to the tables. Similary how can we find out the user name by using the table name known? Any help is appreciated. Thanks Aleem

  • Httpd 2.2.22 released

    Hi all, we have released httpd 2.2.22 some days ago, and NetWare binaries are up on the mirrors: http://httpd.apache.org/download.cgi#apache22 this release contains a couple of security fixes; see also CHANGES: http://artfiles.org/apache.org//httpd/C

  • Adobe dreamweaver cs5 creating your first website part 2

    I'm trying to do the study creating your first website 2 but I have a problem. Maybe I'm stupid but all the time they are talking about figures but I don't see any picture. In part 1 they where there but in part 2 I see or find no pictures or figures

  • IMovie 4 only records ~8 second clips when transfering VHS via Sony DCRHC32

    I am attempting to transfer old VHS tapes directly to my Powerbook using iMovie 4.01. When I start the process using the Sony DCR-HC32 using the analog passthrough feature, I click import and iMovie begins fine but then after about 8 seconds, stops w