Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / September 2006

Tip: Looking for answers? Try searching our database.

Reading integer values from a txt file and save them into an array

Thread view: 
zigbeedeep@gmail.com - 29 Sep 2006 03:02 GMT
Hello,

I would like to read integer values from a txt file :

sam.txt

66 78 99 90
23 34 56 78
12 45 78 09

and save them into an array

Sam
Dan Andrews - 29 Sep 2006 03:38 GMT
> Hello,
>
[quoted text clipped - 9 lines]
>
> Sam

Hi Sam,

The cool thing about many of the Reader and Stream objects in the
java.io package is that you can chain them together for the desired
results. Try something like this:

  public static List<Integer> getIntegersFromFile(
      String fileName) throws IOException {
    StringWriter writer = new StringWriter();
    BufferedReader reader = new BufferedReader(
        new FileReader(fileName));
    for (String line = reader.readLine(); line != null; line = reader
        .readLine()) {
      writer.write(line + " ");
    }
    StringTokenizer tokens = new StringTokenizer(writer
        .toString());
    List<Integer> list = new ArrayList<Integer>();
    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.");
      }
    }
    // If you wanted an int array
    // int[] array = new int[list.size()];
    // for( int i = 0; i < array.length; i++){
    //   array[i] = list.get(i);
    // }
    return list;
  }

Cheers,

Dan Andrews
- - - - - - - - - - - - - - - - - - - - - - - - -
Ansir Development Limited http://www.ansir.ca
- - - - - - - - - - - - - - - - - - - - - - - - -


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.