Help reading file into array

Hi, could any one give me some tips on how to fill this array from a file (data.txt) on the computer that reads:
50 99 44 35 37 22 12 19 7 44
77 64 23 52 59 62 85 98 5 100
72 70 60 50 43 30 20 10 91 1
11 31 81 98 61 13 21 25 44 10
The values are 1-100 but the program's array should have 10 spots. This is what I have so far but I'm confused about what I'm doing:
public static void main(String[] args)
EasyReader console = new EasyReader();
     final int MAX = 100;
     int [] values = new int [MAX];
     int [] numberValues = new int [10];
     // EasyReader File23 = new EasyReader("D:\\data.txt");
     // String value= File23.readLine();
     //System.out.print(value);
     int logicalLength;
     logicalLength = fillArray(numberValues);
     System.out.print(logicalLength);
     public static int fillArray(int []numberValues)      
     EasyReader File23 = new EasyReader("D:\\data.txt");
          int LL = 0;
          int xy= File23.readInt();
          while (!File23.eof())
               numberValues[LL] = xy;
               LL++;
               xy = File23.readInt();
               File23.close();
               return LL;
     }     

thanks for the tip:
Any tips on how to fill this array from a file (data.txt) on the computer that reads:
50 99 44 35 37 22 12 19 7 44
77 64 23 52 59 62 85 98 5 100
72 70 60 50 43 30 20 10 91 1
11 31 81 98 61 13 21 25 44 10
The values are 1-100 but the program's array should have 10 spots. This is what I have so far but I'm confused about what I'm doing (there is an exception in the main too):
public static void main(String[] args)
EasyReader console = new EasyReader();
final int MAX = 100;
int [] values = new int [MAX];
int [] numberValues = new int [10];
int logicalLength;
logicalLength = fillArray(numberValues);
System.out.print(logicalLength);
public static int fillArray(int []numberValues)
EasyReader File23 = new EasyReader("D:\\data.txt");
int LL = 0;
int xy= File23.readInt();
while (!File23.eof())
numberValues[LL] = xy;
LL++;
xy = File23.readInt();
File23.close();
return LL;
}

Similar Messages

  • Read file into multi-dimensional array - ideal world...

    Hello all, would be very grateful if you could help me...
    I have a file which has a format...
    string1a,string1b
    string2a,string2bi need to read this file, which will have a variable length, into a two dimensional array.
    the code below is just demonstrating my approach...
              List lines = new ArrayList();
              BufferedReader in = new BufferedReader(new FileReader(filename));
              String str;
              while ((str = in.readLine()) != null) {
                   lines.add(str.split(","));
              in.close();but when i later try and invoke the toArray() method of lines it complains about unsafe or unchecked operations.
    does any have any pointers about the best way to read a file into a multi-dimensional array? is it best practice to use the interface List?
    thanks in advance
    poncenby

    This is just a List of Lists - no worries there.
    Sounds like your toArray code is incorrect. Post that.
    %

  • Reading files into an array

    so im new to this and having problems.
    we have to read a .txt file into an array so when a user types a word in a text box it will search the file and reutrn found if the word is there and not found it the word is not there. but it is not reading the text file here is the code so far
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class Checker
    // Declares Values in the array
         static String [] anArray = new String[1000];
         // declares variables needed in code later
         int i;
         String s;
         static int count = 0;
         static String b;
         static JTextArea j = new JTextArea();
         public void readFile() throws IOException{
         File inFile = new File("words.txt");
         FileReader fileReader = new FileReader(inFile);
    BufferedReader bufReader = new BufferedReader(fileReader);
    while (true){
    b = bufReader.readLine();
    anArray[count] = b;
    count++;
    if(b==null) throw new EOFException("Hello, end of file reached");
    j.append(b);
    j.append("\n");
         // public static void main(String args[]){
         // File outFile = new File("words.txt");
         //FileOutputStream outFileStream = new FileOutputStream(outFile);
         // PrintWriter outStream = new PrintWriter(outFileStream);
         // outStream.println("help");
    // File inFile = new File("words.txt");
    // FileReader fileReader = new FileReader(inFile);
    // BufferedReader bufReader = new BufferedReader(fileReader);
    /* while (true){
    b = bufReader.readLine();
    anArray[count] = b;
    count++;
    if(b==null) throw new EOFException("Hello, end of file reached");
    j.append(b);
    j.append("\n");
    public String checkword(String Word ) {
    // Tries the code, runs through until an exception is found.
    try {
    for ( i = 0; i < anArray.length; i++)
    if (Word.equals(anArray))
    // If exception is found, throws a new exception
    if (Word.equals(anArray[i])) throw new Exception(); // end if
    } // end if
    } // end for
    } // end try
    catch (Exception ae ) {
    // if the word is found return a message found and its position in array.
    return "Found, at position "+i;
    }// end catch
    // if its not in the array return a not found message
    return "Not found";
         } // end
    } // end
    and the gui class :
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class CountDown extends JFrame implements ActionListener
    // Defines the GUI components
    private JTextField Word = new JTextField(9);
    private JButton Guess = new JButton("Enter String");
         private JLabel Message = new JLabel("not found");
         // Creates a new instance of the Checker class.
    Checker ch = new Checker();
    public CountDown() // constructor
    setTitle("Count Down");
    setSize(300,200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    Container c = getContentPane();
    c.setBackground(Color.white);
    c.setLayout(new GridLayout(3,1));
    // Add the components
    c.add(Word);
    c.add(Guess);
    c.add(Message);
    c.add(ch.j);
    // Add action Listener for Button to work
    Guess.addActionListener(this);
    pack();
    setContentPane(c);
    public void actionPerformed(ActionEvent e) {
    // When the button is pressed do this code
    if(e.getSource() == Guess)
    // Looks in the checker class to compare the word user enters, to the words in the array.
    // Returns a message if the word exists with its position in the list or
    // Returns a message if the word does not exisit.
    Message.setText( ch.checkword(Word.getText()));
    public class CountDownA
    public void main(String[] args)
    CountDown Game = new CountDown();
    any help is appriciated asap

    Yuck! I echo jverd's sentiment. Please only post the specific pieces of code that you are having trouble with, and use the forum 'code' tags.
    But to answer your question, I don't see where you're calling the readFile() method from. If you're not calling readFile, that might explain why nothing is being read.
    As for the design of the readFile method, another 'yuck'. heh Don't use exceptions to break out of a loop. If you MUST break out of a loop, use break. But a loop like this doesn't need break. Try something like this:while( (b = bufReader.readLine()) != null)
         anArray[count++] = b;
         j.append(b+"\n");
    }Also, in stead of creating an array of some arbitrary fixed length, I recommend using a collection class such as ArrayList.
    In stead of this:static String [] anArray = new String[1000];
    anArray[count++] = b;it would be better to use something like this:static ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add(b);

  • Need help importing files into Dreamweaver CS5.5

    Greetings,
    Currently I have website that is hosted on GoDaddy.com http://www.4thdist.org/home.php  . This site was created by another person that is not available to help with my problem. I am attempting to modify or edit this website using Dreamweaver CS5.5 and having difficulties loading the files into Dreamweaver.
    First, using Filezilla I downloaded all the files and folders to my PC. At this point, I am stuck and cannot figure out how to upload or open the files and really need some advice. I read the Adobe help section on "importing" and it describes a .ste file. I searched the download folder and cannot find any file (*.ste)
    I am hoping to salvage the site and not have to reinvent the wheel and start over. Any advice would be extrmely helpful........Gary

    Thanks for the quick reply.
    Your comments raised some new questions. Let me update all on where I am. First, I am able to connect to GoDaddy server via the the local and remote views in the bottom right corner of DW. I see the file folder structure on GoDaddy. I can also see the file structure on my local hardrive that I copied using filezilla. Although, using the server connection I notice that I can download the files using this connection now. Should I delete what I did via filezilla and start over using the romote server connection? One more problem. I have content for two (2) websites on the remote server. http://www.vfwstatepoolleague.org/ This is in addition to the listed in my original post. Although, it appears the other website content is in a seperate folder. I assume that I will need to separtate this content somehow. At least link to it when I begin to start to create a .ste file for each site.
    I started to read the article "Creating your first website"in your post and should be very helpful. I did run into a little road block.
    I created (2) site names and linked to the appropriate folder on my hard drive. Although, I do not have: "check_cs5" folder on my local or remote folder. What does that mean? Should I create one?

  • Read file into a table

    Is there a way of reading content of a file into a table? what if that file is overwritten each x minutes for update?

    yes sure.
    JSplitPane's can hold two components - so your table can be one of the components, and some other feature e.g. a JPanel (which is containing other components in turn) is the other component.
    e.g.
    JSplitPane mainSplitPane_LeftRight = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); // or JSplitPane.VERTICAL_SPLIT
    mainSplitPane_LeftRight.setOneTouchExpandable(true); // set whether you want to be able to maximize one of the components in the JSplitPane using a button on the divider
    // component 1 of splitpane
    JTable yourTable = new JTable(); // initialise with your code here
    // component 2 of splitpane
    JTree tree = new JTree(); // example component
    yourTable.setMinimumSize(new Dimension(10, 10)); // this ensures we can always move the dividers
    tree.setMinimumSize(new Dimension(10, 10)); // this ensures we can always move the dividers
    // add the components
    mainSplitPane_LeftRight.setLeftComponent(yourTable);
    mainSplitPane_LeftRight.setRightComponent(tree);
    // then now we have a populated JSplitPane which you may wanna shove into a JFrame??
    JFrame frame = new JFrame("Tester");
    frame.getContentPane().add(mainSplitPane_LeftRight);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.show(); // show it.Hope that helped.

  • Reading file into itab

    I have to read a text file into my data objects until the end of file. I need help with this syntax
    do
    read dataset file into strfile
    while end of file ?

    Hi Megan,
    Hope this code helps you.
    Start-of-selection.                         
      open dataset fname for input in text mode.                    
      if sy-subrc <> 0.                                             
        message s999(z1) with 'File not found or cannot be opened'. 
        stop.                                                       
      endif.                                                        
      do.                                                           
        read dataset fname into i_upload.                           
        if sy-subrc <> 0.                                           
          exit.                                                     
        endif.                                                      
        append i_upload.                                            
        clear  i_upload.                                            
      enddo.                                                        
      close dataset fname.                                          
    Thanks,
    Srinivas

  • Help reading file

    I put my DES key in a text file and stored within one of the java source folder like com.xyz.order.file.key
    how do I read this file? It's saved in local hard drive. Thanks.

    Either the path is wrong or the desired resource is actually not in the classpath.
    That said, why are you reading it into a fixed length byte array? Is that file always 16 bytes long?
    Still, the aforementioned IO tutorial is really worth reading. For sure in your case. Go read it.

  • Reading file into TYPE RECORD

    I have TYPE RECORD defined as
    TYPE IN_REC IS RECORD
    (field1 varchar2,
    field2 number,
    field3 date);
    i_rec IN_REC;
    Can I read a text file directly into in_rec or i_rec using
    utl_file.get_line(file_handler,in_rec) or
    utl_file.get_line(file_handler,i_rec)
    Please advise, basically I want to load the file into a data structure.
    Thx

    OK, I have to do some valiadations and append data to that text file and write it out so would still go via this route.
    So if I declare
    s varchar2(50);
    and then
    utl_file.get_line(f,s);
    Can I extract the individual fields like this
    inp_rec.field1 := substr(s,1,9);
    Thx

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

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

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

  • Tab Delimited data from file into array

    Could someone give me a full example of how to pull strings out of a text file and insert into an array. I have posted a couple of times and the segments of code that I get back isn't working. I don't know where I am going wrong exactly, so I would like to see a full example. Here is what I posted last.
    I don't want to use a loop. I want to specify what each array element is and how may there are before it is run.
    import java.util.StringTokenizer;
    import java.io.*;
    public class ReadDataFile
    public static void main(String args[])
    try
    FileReader fr = new FileReader("DataFile");
    BufferedReader br = new BufferedReader(fr);
    String s;
    String data[] = new String[12];
    int count = 0;
    while((s = br.readLine()) != null)
    StringTokenizer st =new StringTokenizer(s);
    data[0] = st.nextToken();
    data[1] = st.nextToken();
    data[2] = st.nextToken();
    data[3] = st.nextToken();
    data[4] = st.nextToken();
    data[5] = st.nextToken();
    data[6] = st.nextToken();
    data[7] = st.nextToken();
    data[8] = st.nextToken();
    data[9] = st.nextToken();
    data[10] = st.nextToken();
    data[11] = st.nextToken();
    data[12] = st.nextToken();
    System.out.println(data[3]);
    catch(IOException ioe)
    System.out.println(ioe.getMessage());
    With this I get this error when I try to run it.
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(StringTokenizer.java:235)
    at ReadDataFile.main(ReadADataFile.java:37)
    Thanks

    Just return String array instead of returning vector and change tokanizer according to ur requirement
    public Vector valuesarr(HttpServletRequest req, HttpServletResponse res,String user,String filename,String folder)
                        PrintWriter out =null;
                        boolean indbool=false;
                        boolean fd=false;
              try{
                             out = res.getWriter();
                        BufferedReader br =null;
                        String     fl=folder+"/txt/"+filename+".txt";
                        File tt = new File(fl);
                   String s, s2 = new String();
                        String userval;
                        String files;
                        int ind=0;
                        boolean indigo=true;
                        Vector v=new Vector();
                        if( tt.exists() )
                             String mainarr[]=null;
                             br = new BufferedReader(new FileReader(fl));
                                  while((s = br.readLine())!=null)
                                            s2=s+"\n";
                                            if (s.indexOf(user) > -1)
                                                 ind=s.indexOf(user);
                                                 StringTokenizer st = new StringTokenizer(s,";=");
                                                 String [] filearr1=new String[s.length()];
                                                 int t=0;
                                                      while(st.hasMoreTokens())
                                                           String stfiles1=st.nextToken();
                                                           filearr1[t]=stfiles1;
                                                           t++;
                                                 String filearr2 []=new String[t];
                                                      for( int a=0;a<t;a++)
                                                           if(filearr1[a]!=null)
                                                           v.addElement(filearr1[a]);          
         return v;
    }catch(FileNotFoundException f)
         out.println(f.getMessage());
         return null;
         catch(IOException io)
              out.println(io.getMessage());
              return null;

  • 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

  • Streaming data to disk, need help reading data into Power Spectrum/O​ctave vi

    I'm streaming data to disk in one loop, however once this finishes I'd like to read the data into power spectrum vi/Octave analysis vi in another loop. The data from the read vi is a string and power spectrum vi needs 1d waveform. Does anyone have experience with this process?

    From your general description, I gather you are streaming to a text based file (comma or tab separated spreadsheet format) and would like to analyse this data with a power spectrum or octave analysis when you finish. Since you are streaming, I assume you have a lot of data. Do you have more than one channel?
    In any case, you have two simple options (and lots of complex ones). You can either read the data back from disk and convert it to a 1D array (try the Read From Spreadsheet File.vi - will get a 2D array, take the first column or the column of your choice if you have more than one channel) or you can use the Spreadsheet String to Array primitive to create an array from your text data before you save it to disk.
    If your data rate is slow enough, you can analyze as you acquire and store.
    Taking your data as text is very inefficient. What you really want to do is read the data as binary, use that for your analysis, and use something like the Write to Spreadsheet File.vi to save text data to disk.
    This account is no longer active. Contact ShadesOfGray for current posts and information.

  • Can not convert this .tif file into array?

    Dear all:
    I am driven crazy by a set of image files. It is a .tif format file. I could open it fine in ImageJ however when I tried to open it in Labview and tried to convert it from .tif to a 2d array. I noticed that a lot of the data are out of the range and to my surprise, some data are negative valued. I checked in ImageJ and it is not showing any negative pixel values.
    I am attaching some snapshots and the original file. Please help me or any advice would be appreciated.
    Seems that there are some file type problems.
    Attachments:
    questions NI forum front.JPG ‏155 KB
    questions NI forum back.JPG ‏40 KB

    Put the TIFF in a ZIP file and you can post it.  You probably won't get much compression, but the forums will then accept it.
    This account is no longer active. Contact ShadesOfGray for current posts and information.

Maybe you are looking for

  • Web Service Homepage: Authority check failed

    Dear Colleagues, I have created a Web Service and now I want to test it via its Web Service Homepage (TA WSADMIN). The Homepage is displayed correctly, but testing leads to an error: Authority check failed Are there any prerequisites I maybe do not a

  • MaxT3MessageSize in Weblogic 5.1

    I'm trying to set the maximum size for a T3 message using weblogic 5.1, but am unable to find any reference to this parameter using wls 5.1. Did this parameter exist back then? I need to send large JMS messages to a wls 5.1 server.           Thanks  

  • All attachments now blue boxes with question marks

    Something happened over the weekend to Apple Mail on my laptop... ALL attachments now just show up as funky little blue boxes the question marks. Instead of showing me a JPEG, PNG, or PDF inline in the message, it's just a little blue box. If it's an

  • Problem connecting to SQL Server from JDeveloper 10g using jdbc third party

    I am using Oracle 10g Jdeveloper and I tried to setup a database connection to SQL Server using various Drivers for JDBC as Merlin, jtds, inet.tds, etc. (I had no problem to set up a connection to an Oracle Database using the Oracle JDBC driver). Whe

  • Changing Date Format in query panel default calender

    Hi All, when I drag the date into the Query Filter Panel in Webi and use the between operator (or any operator) the format of the date shows up as DD/MM/YYYY as default . But we want the format should show up as DD/MM/YYYY HH24:MM:SS As far as we kno