Read a text file into array

Can anyone let me know how to get read the values column wise from the text file and put each column in each arrays.
for eg: if we have 4 columns in the text file then the values will be stored in 4 arrays.
Thanks in advance
Regards
Kutty

Use a two dimensional array to store your data, and use the StringTokenizer class to split up the lines as you read them in from the file.

Similar Messages

  • Reading text file into array

    Hi, I'm reading a text file that is as follows:
    7
    5.5
    15
    5.35
    30
    6.5
    I have the file reading in fine, but am extremely confused on how to read each line to read into a different variable.
    the whole numbers are the term of a loan and the doubles are the interest rate.
    I have read through several of the existing posts on reading the file, but am still have problems.
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    public class ReadFile extends JFrame
         public static void main (String[] arguments) throws IOException
                   String line;            
                    BufferedReader input;
                   input = new BufferedReader (new FileReader ("MortgageValues.txt"));
                   String Term;
                   String Rate;
                        while ((line = input.readLine()) != null)
                      Term = input.readLine ();
                           System.out.println(line);
              input.close ();
    }     

    the whole numbers are the term of a loan and the
    doubles are the interest rate.Oh! Your problem seems to be reading alternate values. Here's a piece of code for that :)
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    public class Test7 {
        public static void main(String[] args) throws Exception {
            String line        = null;
            int count          = 0;
            StringBuffer Term  = new StringBuffer();
            StringBuffer Rate  = new StringBuffer();
            BufferedReader input = new BufferedReader (new FileReader ("MortgageValues.txt"));
            while ((line = input.readLine()) != null) {
                if(count%2 == 0) Term.append(line).append(",");
                else        Rate.append(line).append(",");
                count++;
            Term.deleteCharAt(Term.length() -1);
            Rate.deleteCharAt(Rate.length() -1);
            System.out.println("Term>>>" +Term);
            System.out.println("Rate>>>" +Rate);
            input.close ();
    }

  • Parse Text-File into array

    Hi,
    I hava a text-file with a structure like this.
    "sfdgasdf" "sadsadsadf" "sadfsdfasfd"
    "qwevsdf" "sdgfasdfsafd" "yxvcyxvcyxvc"
    "hgfddfhhfdfdf" "ewrtqwrwqewqr" "dfgdgdgsdgsdfgsdgg"
    My aim is to read this text-file (*.txt) and parse it into an string-array (or whatever is the best). The contents between the apostrophes should be inserted in this array line by line.
    For example:
    array[0][0] = "sfdgasdf";
    array[0][1] = "sfdgasdf";
    array[0][1] = "sadfsdfasfd";
    array[1][1] = "qwevsdf";
    How can I achieve this?
    Thanks
    Jonny
    That's how far i came (not very far).
    File file = new File("c:\temp\text.txt");
    FileReader stream = new FileReader(file);

    Hi,
    still facing some problems.
    My text which I want to parse:
    "sfdgasdf" "sadsadsadf" "sadfsdfasfd"
    "qwevsdf" "sdgfasdfsafd" "yxvcyxvcyxvc"
    "hgfddfhhfdfdf" "ewrtqwrwqewqr" "dfgdgdgsdgsdfgsdgg"
    My code:
    String[] parse = text.split("\"");
    The array that is created has whitespaces and linebreaks as elements. I only want the characters in beween the apostrophes.
    How can I "tell" the split function not to insert them in my array?
    Cheers
    Jonny

  • Open and read from text file into a text box for Windows Store

    I wish to open and read from a text file into a text box in C# for the Windows Store using VS Express 2012 for Windows 8.
    Can anyone point me to sample code and tutorials specifically for Windows Store using C#.
    Is it possible to add a Text file in Windows Store. This option only seems to be available in Visual C#.
    Thanks
    Wendel

    This is a simple sample for Read/Load Text file from IsolateStorage and Read file from InstalledLocation (this folder only can be read)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Storage;
    using System.IO;
    namespace TextFileDemo
    public class TextFileHelper
    async public static Task<bool> SaveTextFileToIsolateStorageAsync(string filename, string data)
    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(data);
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
    try
    using (var s = await file.OpenStreamForWriteAsync())
    s.Write(fileBytes, 0, fileBytes.Length);
    return true;
    catch
    return false;
    async public static Task<string> LoadTextFileFormIsolateStorageAsync(string filename)
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    string returnvalue = string.Empty;
    try
    var file = await local.OpenStreamForReadAsync(filename);
    using (StreamReader streamReader = new StreamReader(file))
    returnvalue = streamReader.ReadToEnd();
    catch (Exception ex)
    // do somthing when exception
    return returnvalue;
    async public static Task<string> LoadTextFileFormInstalledLocationAsync(string filename)
    StorageFolder local = Windows.ApplicationModel.Package.Current.InstalledLocation;
    string returnvalue = string.Empty;
    try
    var file = await local.OpenStreamForReadAsync(filename);
    using (StreamReader streamReader = new StreamReader(file))
    returnvalue = streamReader.ReadToEnd();
    catch (Exception ex)
    // do somthing when exception
    return returnvalue;
    show how to use it as below
    async private void Button_Click(object sender, RoutedEventArgs e)
    string txt =await TextFileHelper.LoadTextFileFormInstalledLocationAsync("TextFile1.txt");
    Debug.WriteLine(txt);
    在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。

  • Convert a line read from text file into string

    how to convert a line from text file into string?
    i know how to convert to numbers,
    private int  parseLine1(String line) {
              StringTokenizer tokenizer = new StringTokenizer(line);
                  value1 = Integer.valueOf(tokenizer.nextToken()).intValue();
                  value2 = Integer.valueOf(tokenizer.nextToken()).intValue();
                 return value1;
                     }but what about charactrs?

    ok, here is my problem, i have a file with a bunch of Xs in it but position function doesn't return a correct value, what's going wrong?
    private int positioni(){
           int i=0;
           int j=0;
           int b=0;
           String line="";
            while(line!= null){
                for(int a=0; a<line.length(); a++){
                    if(line.charAt(a)=='X'){
                        i=a;}
                b++;
                j=b;
                t=line.length();
                line=read(gridFileN);
           return i;
    private String read(String ggridFileN){
             TextStreamReader ggridFile = new TextStreamReader(ggridFileN);
             return ggridFile.readLine();

  • Reading a text file into a StringBuffer?

    Hey all,
    I've taken a year of Java programming class so far, but I doubt my class is ever going to get in to things like this. I've been trying to develop a program that reads a small text file into a StringBuffer for manipulation and use in the program. I've been looking around the web, but thus far all I've seen are things like FileInputStream, in the java.io.* package; nothing about StringBuffers.
    And I'm pretty sure it's kind of hard, too. If someone could give me a simple(?) explanation, or a link to a tutorial that shows you this or something, it would be much appreciated.
    Also, is it possible to pull an integer out of a string? I was just wondering this, I don't think you can cast a string to an int or anything. Ha ha.
    ~Darkslime, Java student

    Hey all,
    I've taken a year of Java programming class so far,
    but I doubt my class is ever going to get in to
    things like this. I've been trying to develop a
    program that reads a small text file into a
    StringBuffer for manipulation and use in the program.
    I've been looking around the web, but thus far all
    I've seen are things like FileInputStream, in the
    java.io.* package; nothing about StringBuffers.
    And I'm pretty sure it's kind of hard, too. If
    someone could give me a simple(?) explanation, or a
    link to a tutorial that shows you this or something,
    it would be much appreciated.
    Also, is it possible to pull an integer out of a
    string? I was just wondering this, I don't think you
    can cast a string to an int or anything. Ha ha.
    ~Darkslime, Java student
    try {
            BufferedReader in = new BufferedReader(new FileReader("infilename"));
            String str;
            while ((str = in.readLine()) != null) {
                process(str);
            in.close();
        } catch (IOException e) {
        }

  • Still having trouble with reading text file into array

    Hi, This is from another post, I have tried one of the solutions that were provided, but got the following error at runtime:
    C:\j24work>java Test7
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException
    at java.lang.StringBuffer.deleteCharAt(StringBuffer.java:681)
    at Test7.main(Test7.java:26)
    My code is attached. My text file reads as follows:
    7 5.5 15 5.35 30 6.5
    The first , third and fifth numbers should ultimately be int values representing the term of a mortgage. The second, fourth and sixth numbers ultimately need to be doubles representing the rate on a mortgage. Do I need a 2d array??
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    public class Test7 {
        public static void main(String[] args) throws Exception {
            String line        = null;
            int count   = 0;
            StringBuffer Term  = new StringBuffer();
            StringBuffer Rate  = new StringBuffer();
            BufferedReader input = new BufferedReader (new FileReader ("MortgageValues.txt"));
            while ((line = input.readLine()) != null) {
                if(count%2 == 0) Term.append(line).append(",");
                else        Rate.append(line).append(",");
                count++;
            Term.deleteCharAt(Term.length() -1);
            Rate.deleteCharAt(Rate.length() -1);
            System.out.println("Term>>>" +Term);
            System.out.println("Rate>>>" +Rate);
           // input.close ();
        }

    Okay, modify the code as below:
    import java.io.*;
    import java.util.*;
    public class Test7 {
        public static void main(String[] args) throws Exception {
            String line             = null;
            StringTokenizer strTok  = null;
            int count          = 0;
            StringBuffer term  = new StringBuffer();
            StringBuffer rate  = new StringBuffer();
            BufferedReader input = new BufferedReader (new FileReader ("MortgageValues.txt"));
            while ((line = input.readLine()) != null) {
                strTok = new StringTokenizer(line);
                while(strTok.hasMoreTokens()) {
                    if(count%2 == 0)    term.append(strTok.nextToken()).append(",");
                    else                rate.append(strTok.nextToken()).append(",");
                    count++;
            term.deleteCharAt(term.length() -1);
            rate.deleteCharAt(rate.length() -1);
            System.out.println("term>>>" +term);
            System.out.println("rate>>>" +rate);
           input.close ();
    }Cheers!
    ***Annie***

  • Reading a text file into a clob

    Hi guys,
    I'm trying to read in a text file and store it in an Oracle database as a CLOB. However, I'm trying it with a 200K file and it takes ages and then produces this:
    java.sql.SQLException: Io exception: Software caused connection abort: socket write error
    Here is my code:
    conn.setAutoCommit(false);
    String query = "insert into tests (ScriptID, Test) values (?, ?)";
    PreparedStatement insertTests = conn.prepareStatement(query);
    insertTests.setInt(1, scriptID);
    insertTests.setCharacterStream(2, new java.io.FileReader(test), (int) test.length());
    insertTests.executeUpdate();
    insertTests.clearParameters();
    conn.setAutoCommit(true);I've also tried using
    insertTests.setAsciiStream(2, new java.io.FileInputStream(test), (int) test.length()); (as recommended at http://otn.oracle.com/sample_code/tech/java/codesnippet/jdbc/lob/LobToSP.html) but this produces a different exception (java.sql.SQLException: Io exception: Char array not long enough: javaCharsToUtf8Bytes)
    Any help with this problem would be greatly appreciated.
    Cheers!
    sirdavidoff

    I know there were some problems writing larger files with the thin driverI think the issue has to do with the 4k limit, anything over 4000 must be done in chunks of 4000.
    ;o)
    V.V.

  • Reading a text File into a JTextArea

    I know this is really basic question, but what is the best and/or simplest way to read text from a .txt file into a JTextArea? I'm new to Java and any help anyone can provide would be greatly appreciated.

    it should be in quotes only if it is a string repersentation of a String class.
    FileReader reader = new FileReader("readme.txt");
    quotes are not needed if you write it this way
    String filename = "readme.txt";
    FileReader reader = new FileReader(filename);
    ...remember that String is a class and not a data type, it is also a special case in java where the class can act like a datatype in declarations.
    I don't think anything else can behave like this in java
    String text = "sometext";
    "sometext".equals(text);
    this returns true.

  • Read a text file into a map?

    I need to create a map that looks something like this:
    temp0 -> A
    temp1 -> A
    temp2 -> B
    temp3 -> C
    temp4 -> B
    temp5 -> A
    temp6 -> C
    Now instead of implementing this in a .java file (that needs to be compiled) I was wondering if there was some way to just define the mapping in a plain text file and then read it into a map when needed.
    I know how to read tokens using the tokenizer, but are there any java tools specially made for this purpose?

    You might be interested in [the Properties class|http://java.sun.com/javase/6/docs/api/java/util/Properties.html].

  • How to read\write text file into oracle database.

    Hello,
    I am having text file called getInfo in c:\temp folder. I would like to populate data from text file to data base. How to proceed. Could anybody help me out.
    Thanks,
    Shailu

    Here is a web page with easy to follow instructions regarding external files: http://www.adp-gmbh.ch/ora/misc/ext_table.html.
    Now I understand what all the excitement is over external tables.
    "External tables can read flat files (that follow some rules) as though they were ordinary (although read-only) Oracle tables. Therefore, it is convenient to use external tables to load flat files into the DB." -from the above link.

  • Reading a text file into a program

    Hi
    First off I am new to this and know very little about Cocoa programming. I have followed some tutorials e.t.c. and can make basic applications but I have a project I am doing which requires more knowledge than I have.
    The problem: part 1
    I can make a basic 'Hello world' app that has a window and has text in it, but i want this text to be read directly from an external text file. I plan on using a heart rate monitor which will give me information via the serial port and i have written the appropriate applescript to write this data to a text file. I now want a basic cocoa application that will display the contents of this text file as to show the users heart rate.
    This is only the beginning but i figure it's a start, once i have this down i can move onto the real reason behind the project.
    Below is what i found in the ref library. I think it's what i need to be using but i don't know where to put it and where to define the text file that needs to be read.
    "stringWithContentsOfFile:encoding:error:
    Returns a string created by reading data from the file at a given path interpreted using a given encoding.
    *+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError *)error
    Parameters
    path
    A path to a file.
    enc
    The encoding of the file at path.
    error
    If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, pass in NULL.
    Return Value
    A string created by reading data from the file named by path using the encoding, enc. If the file can’t be opened or there is an encoding error, returns nil."
    Below is my code i made using a tutorial. All it does it make a window appear with 'hello world' in it. The idea is to replace the hello world with the text in the external .txt file
    #import "HelloView.h"
    @implementation HelloView
    - (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
    // Initialization code here.
    return self;
    - (void)drawRect:(NSRect)dirtyRect {
    NSString* hello = @"Hello, World!";
    NSPoint point = NSMakePoint(15, 75);
    NSMutableDictionary* font_attributes = [NSMutableDictionary new];
    NSFont* font = [NSFont fontWithName:@"Futura-MediumItalic" size:42];
    [font_attributes setObject:font forKey:NSFontAttributeName];
    [hello drawAtPoint:point withAttributes:font_attributes];
    [font_attributes release];
    @end
    If anyone can help me it would be much appreciated
    Thanks
    Adam

    Hello,
    Well doing that way you just need to put another string in the "hello" container.
    Instead of - (void)drawRect:(NSRect)dirtyRect {
    NSString* hello = @"Hello, World!";
    /...../} you define "hello" another way
    - (void)drawRect:(NSRect)dirtyRect {
    NSString *hello = [NSString stringWithContentsOfFile:@"/Your/Path/Here/" encoding:NSUTF8StringEncoding error:NULL];//Assuming UTF8 encoding
    if ( ! hello)
    hello =@"Failed to load the string";
    NSPoint point = NSMakePoint(15, 75);
    NSMutableDictionary* font_attributes = [NSMutableDictionary new];
    NSFont* font = [NSFont fontWithName:@"Futura-MediumItalic" size:42];
    [font_attributes setObject:font forKey:NSFontAttributeName];
    [hello drawAtPoint:point withAttributes:font_attributes];
    [font_attributes release];
    The "if/else" was there to test successful loading of the file, and give you hints of why in case of failure but you can do without. I changed it so you just report an error occurred to user..
    All that said drawing strings in a window is more often done using a NSTextField in Interface Builder, if you wanna learn Cocoa maybe you should go that way.

  • How to read a text file into a String?

    and also write a text file from a String. I searched the forum and found this folowing code:
    // Read and append... by Example
    try{
    String fileName = "text.txt"; // Filename
    // Make the inputfile object
    FileInputStream fi = new FileInputStream(fileName);
    byte inData[] = new byte[fi.available()];
    fi.read(inData); // Read
    fi.close(); // Close
    String text = new String(inData); // Make a textstring...
    // Now, do whatever you want with the data... and append...
    String textToAppend = "kjkjhjhKJ";
    byte outData[] = textToAppend.getBytes();
    // Make the outputfile (whith the 'append' boolean set to true
    FileOutputStream fo = new FileOutputStream(fileName,true);
    fo.write(outData);
    fo.close();
    }catch(Exception oops){}but it returns funny characters to the String from the text file and vice versa in writting the text file. Can anybody please help? Thank you.
    kindo

    See here for info on encodings:
    http://java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html
    Some common US encodings and common uses:
    ASCII (DOS)
    Cp1252 (Windows 9x)
    UTF8 (XML)
    import java.io.*;
    public class TextFile extends File
    private static String DEFAULT_ENCODING = "ASCII";
    private File file;
    private String encoding;
    public TextFile(File file, String encoding)
         super(file.getPath());
         this.file = file;
         this.encoding = encoding;
    public TextFile(File file)
         this(file, DEFAULT_ENCODING);
    public String load() throws Exception
         FileInputStream fis = new FileInputStream(file);
         byte[] barr = new byte[fis.available()];
         fis.read(barr);
         fis.close();
         return new String(barr, encoding);
    public void save(String str) throws Exception
         FileOutputStream fos = new FileOutputStream(file);
         fos.write(str.getBytes(encoding));
         fos.close();
    }

  • Reading in text file into strings

    Hi,
    I'm new to the reading in data part of java and I can't work out a good way to read in a .txt file and then store each line of the txt file into strings.
    I think I'm probably just missing something obvious but if anyone can help :D!
    Thanks,
    Bex

    Look up Scanner in Java 1.5, or BufferedReader in Java 1.4.

  • Is it possible to read a text file into an applet?

    I have a text file that contains data I want to use in my applet. Is there a way to read in the data?
    Thanks,
    Brad

    With a signed applet you can read a file from the local hard disk. There is a forum for signed applets. The source code of your signed applet will require some additional code (before opening and reading the file, like // create a permission object
    FilePermission perm = new FilePermission("path/file", read);
    // check the permission object
    AccessController.checkPermission(perm);

Maybe you are looking for

  • Major problems setting up a WRT54G as it keeps asking me for a Passphrase i do not know...

    During the course of setting up a WRT54G, it is now asking me for a Passphrase before it will connect wireless to my notebook....  In other words, my notebook detected it and wants a Passphrase to allow the connection. It is like 16 characters long..

  • UIX Master-Detail  - Find button does not display detail lines

    Hello, We have a master-detail UIX page. Master has one attribute only. When 'Next' or 'Previous' buttons are pressed, the next master-detail records are displayed. However, when master attribute's value is changed by the user and the 'Find' button i

  • Applet window

    Hi everyone, I've got an applet that opens a dialog. These dialogs are displayed as java applet windows. I have a problem when using them. If a user clicks a button, they open this applet window (dialog). While this dialog is open, if they click on s

  • Standby database configuration

    I implemented standby database Steps: - Closed database Backup primary database Open primary database in mount stage Create standby control file shutdown the primary database mount the standby db recover it through archive logs But after this when i

  • How to return to previous page

    I have a form A. Once filled out, they should subnmit to insert the data into a table. However, they can fill out the form and not submt. There is a icon in the upper left that will take them to another form B (comments) to fill out. If they submit f