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

Similar Messages

  • Reading from file into an array

    Hello, new to Java and we need to modify a mortgage calculator to read interest rate from a file into an array and not have them hard coded in the program. I have read many post on how to perform this but am lost on where to put the new code and format. Here is my code and I hope I posted this right.
    import javax.swing.*;                                              // Imports the Main Swing Package                                   
    import javax.swing.event.*;
    import javax.swing.text.*;                                          // Used for  Text Box Caret Position
    import java.awt.*;                                                // Imports the main AWT Package
    import java.awt.event.*;                                         // Event handling class are defined here
    import java.text.NumberFormat;
    import java.text.*;                                              // Imports the Main Text Package
    import java.util.*;                                              // Imports the Main Utility Package
    public class mortgageCalculator1 extends JFrame implements ActionListener             // Creates class mortgageCalculator
        JLabel AmountLabel = new JLabel("   Enter Mortgage Amount:$ ");                   // Declares Mortgage Amount Label
        JTextField mortgageAmount = new JTextField(10);                                     // Declares Mortgage Amount Text Field
        JButton IntandTerm1B = new JButton("7 years at 5.35%");                    // Declares 1st Mortgage Term and Interest Rate
        JButton IntandTerm2B = new JButton("15 years at 5.50%");                    // Declares 2nd Mortgage Term and Interest Rate
        JButton IntandTerm3B = new JButton("30 years at 5.75%");                    // Declares 3rd Mortgage Term and Interest Rate
        JLabel PaymentLabel = new JLabel("   Monthly Payment: ");                     // Declares Monthly Payment Label
        JTextField monthlyPayment = new JTextField(10);                          // Declares Monthly Payment Text Field
        JButton exitButton = new JButton("Exit");                              // Declares Exit Button
        JButton newcalcButton = new JButton("New Calculation");                     // Declares New Calculation Button
        JTextArea mortgageTable = new JTextArea(35,65);                         // Declares Mortgage Table Area
        JScrollPane scroll = new JScrollPane(mortgageTable);                         // Declares ScrollPane and puts the Mortgage Table inside
        public mortgageCalculator1()                                        // Creates Method
             super("MORTGAGE CALCULATOR");                              // Title of Frame
             JMenuBar mb = new JMenuBar();                                   // Cretes Menu Bar
                JMenu fileMenu = new JMenu("File");                                 // Creates File Menu
             fileMenu.setMnemonic('F');                                      // Enables alt + f to Access File Menu
             JMenuItem exitItem = new JMenuItem("Exit");                     // Creates Exit in File Menu
             fileMenu.add(exitItem);                                   // Adds Exit to File Menu
                 exitItem.addActionListener(new ActionListener()                     // Adds Action Listener to the Exit Item
                     public void actionPerformed(ActionEvent e)                     // Tests to Verify if File->Exit is Pressed
                         System.exit(0);                                // Exits the Programs when File->Exit is Pressed
                mb.add(fileMenu);                                      // Adds the File Menu
                setJMenuBar(mb);                              
         setSize(600, 400);                                        // Sets Size of Frame
            setLocation(200,200);                                         // Sets the Location of the Window  
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                                  // Command on how to close frame
         JPanel pane = new JPanel();                                   // Declares the JPanel
         pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));                          // Sets Panel Layout to BoxLayout
         Container grid = getContentPane();                               // Declares a Container called grid
         grid.setLayout(new GridLayout(4,3,5,5));                          // Sets grid Layout to GridLayout
         pane.add(grid);                                             // Adds the grid to the Panel
         pane.add(scroll);                                        // Addes the scrollPane to the Panel
            grid.setBackground(Color.yellow);                              // Set grid color to Yellow
         setCursor(new Cursor(Cursor.HAND_CURSOR));                         // Makes the cursor look like a hand
         mortgageAmount.setBackground(Color.black);                         // Sets mortgageAmount JPanel JTextField Background Color
            mortgageAmount.setForeground(Color.white);                         // Sets mortgageAmount JPanel JTextField Foreground Color
         mortgageAmount.setCaretColor(Color.white);                         // Sets mortgageAmount JPanel JTextField Caret Color
         mortgageAmount.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18));     // Sets mortgageAmount JPanel JTextField Font
         monthlyPayment.setBackground(Color.black);                         // Sets monthlyPayment JPanel JTextField Background Color
         monthlyPayment.setForeground(Color.white);                         // Sets monthlyPayment JPanel JTextField Foreground Color
            monthlyPayment.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18));     // Sets monthlyPayment JPanel JTextField Font
         mortgageTable.setBackground(Color.yellow);                         // Sets mortgageTable JTextArea Background Color
         mortgageTable.setForeground(Color.black);                         // Sets mortgageTable JTextArea Foreground Color
         mortgageTable.setFont(new Font("Arial", Font.PLAIN, 18));               // Sets JTextArea Font
         grid.add(AmountLabel);                                        // Adds the Mortgage Amount Label
         grid.add(mortgageAmount);                                   // Adds the Mortgage Amount Text Field
         grid.add(IntandTerm1B);                                        // Adds 1st Loan and Rate Button
         grid.add(PaymentLabel);                                    // Adds the Payment Label
         grid.add(monthlyPayment);                                    // Adds the Monthly Payment Text Field
           monthlyPayment.setEditable(false);                              // Disables editing in this Text Field
            grid.add(IntandTerm2B);                                        // Adds 2nd Loan and Rate Button
            grid.add(exitButton);
         grid.add(newcalcButton);                                    // Adds the New Calc Button
            grid.add(IntandTerm3B);                                        // Adds the Exit Button
         setContentPane(pane);                                          // Enables the Content Pane
         setVisible(true);                                          // Sets JPanel to be Visable
         exitButton.addActionListener(this);                                // Adds Action Listener to the Exit Button
         newcalcButton.addActionListener(this);                            // Adds Action Listener to the New Calc Button
            IntandTerm1B.addActionListener(this);                              // Adds Action Listener to the 1st loan Button
         IntandTerm2B.addActionListener(this);                              // Adds Action Listener to the 2nd loan Button
         IntandTerm3B.addActionListener(this);                               // Adds Action Listener to the 3rd loan Button
         mortgageAmount.addActionListener(this);                              // Adds Action Listener to the Mortgage  Amount Text Field
         monthlyPayment.addActionListener(this);                              // Adds Action Listener to the Monthly payment Text Field
        public void actionPerformed(ActionEvent e)                               // Tests to Verify Which Button is Pressed
            Object command = e.getSource();                                                 // Enables command to get data
            if (command == exitButton) //sets exitButton                         // Activates the Exit Button
                System.exit(0);  // Exits from exit button                         // Exits from exit button
            int loanTerm = 0;                                             // Declares loanTerm
            if (command == IntandTerm1B)                                   // Activates the 1st Loan Button
                loanTerm = 0;                                        // Sets 1st value of Array
            if (command == IntandTerm2B)                                   // Activates the 2nd Loan Button
                loanTerm = 1;                                        // Sets 2nd value of Array
            if (command == IntandTerm3B)                                   // Activates the 3rd Loan Button
             loanTerm = 2;                                        // Sets 3rd value of Array
                double mortgage = 0;                                   // Declares and Initializes mortgage
             double rate = 0;                                        // Declares and Initializes rate                                        
             double [][] loans = {{7, 5.35}, {15, 5.50}, {30, 5.75},};                 // Array Data for Calculation
                    try
                        mortgage = Double.parseDouble(mortgageAmount.getText());            // Gets user input from mortgageAmount Text Field
                      catch (NumberFormatException nfe)                          // Checks for correct number fformatting of user input
                       JOptionPane.showMessageDialog (this, "Error! Invalid input!");      // Outputs error if number is wrong format or nothing is entered
                       return;
             double interestRate = loans [loanTerm][1];                         // Sets interestRate amount
             double intRate = (interestRate / 100) / 12;                         // Calculates Interst Rate     
                double loanTermMonths = loans [loanTerm] [0];                    // Calculates Loan Term in Months
                int months = (int)loanTermMonths * 12;                          // Converts Loan Term to Months
                double interestRateMonthly = (intRate / 12);                                // monthly interst rate
             double payment = mortgage * intRate / (1 - (Math.pow(1/(1 + intRate), months)));    // Calculation for Monthly payment
                double remainingLoanBalance = mortgage;                              // Sets Reamaining Balance
                double monthlyPaymentInterest = 0;                                       // holds current interest payment
                double monthlyPaymentPrincipal = 0;                                    // holds current principal payment
                NumberFormat myCurrencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);     // Number formatter to format output in table
                monthlyPayment.setText(myCurrencyFormatter.format(payment));
                mortgageTable.setText("Month\tPrincipal\tInterest\tEnding Balance\n" +                // Formats morgageTable Header
                                      "---------\t----------\t------------\t---------------------\n");
                    for (;months > 0 ; months -- )
                     monthlyPaymentInterest = (remainingLoanBalance * intRate);               // Calculation for Monthly Payment Toward Interest
                     //Calculate H = R x I
                     monthlyPaymentPrincipal = (payment - monthlyPaymentInterest);          // Calculation for Monthly Payment Toward Principal
                     //Calculate C = P - H
                  remainingLoanBalance = (remainingLoanBalance - monthlyPaymentPrincipal);     // Calculation for Reamining loan Balance
                  // Calculate R = R - C
                  // H = monthlyPaymentInterest
                  // R = remainingLoanBalance
                  // P = payment
                  // C = monthlyPaymentPrincipal
                  // I = interestRateMonthly
                  mortgageTable.setCaret (new DefaultCaret());                    // Sets Scroll position to the top left corner
                  mortgageTable.append(String.valueOf(months) + "\t" +               // Pulls in data and formats MortgageTable
                  myCurrencyFormatter.format(monthlyPaymentPrincipal) + "\t" +
                     myCurrencyFormatter.format(monthlyPaymentInterest) + "\t" +
                     myCurrencyFormatter.format(remainingLoanBalance) + "\n");
                           if(command == newcalcButton)                               // Activates the new calculation Button
                         mortgageAmount.setText(null);                         //clears mortgage amount fields
                      monthlyPayment.setText(null);                         //clears monthly payment fields
                            mortgageTable.setText(null);                              //clears mortgage table
    public static void main(String[] args)                               //This is the signature of the entry point of all the desktop apps
         new mortgageCalculator1();
    }

    OK, making a little progress but am still very confused.
    What I have is a file (int&term.dat) with three lines;
    5.75, 30
    5.5, 15
    5.35 ,7
    I have three JButtom that I what to read a seperate line and place the term in a term TextField and a rate in a Rate TextField
    I have added the following code and all it does now is output a black space to the screen; I am working with one Button and Just the rate for now to try and get it to work. I have been looking at the forums, reading the internet and several books to try and figure this out. I think I may be getting closer.
    public static void read()
        String line;
        StringTokenizer tokenizer;
        String rate;
        String term;
        try
            FileReader fr = new FileReader ("int&term.dat");
            BufferedReader inFile = new BufferedReader (fr);
            line = inFile.readLine();
            while (line != null)
            tokenizer = new StringTokenizer(line);
            rate = tokenizer.nextToken();
            line = inFile.readLine();
             inFile.close();
             System.out.println(new String());
             catch (FileNotFoundException exception)
                   System.out.println ("The file was not found.");
              catch (IOException exception)
                    System.out.println (exception);
    }

  • 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 large binary files into an array for parsing

    I have a large binary log file, consisting of binary data separted by header flags scattered nonuniformly thorughout the data.  The file size is about 50M Byte.  When I read the file into an array, I get the Labview Memory full error.  The design of this is to read the file in and then parse it fro the flags to determine where to separate the data blocks in the byte stream. 
    There are a few examples that I have read on this site but none seem to give a straight answer for such a simple matter.   Does anyone have an example of how I should approach this?

    I agree with Gerd.  If you are working with binaries, why not use U8 instead of doubles.
    If the file is indeed 50MB, then the array should be expecting 52428800 elements, not 50000000.  So if you read the file in a loop and populate an element at a time, you could run out of memory fast because any additional element insertion above 50000000 may require additional memory allocation of the size above 50000000 (potentially for each iteration).  This is just speculation since I don't see the portion of your code that populates the array.
    Question:  Why do you need an array?  What do you do with the data after you read it?  I agree with Altenbach, 50MB is not that big, so working with a file of such a size should not be a problem.

  • How to read sampled data info from a "*.au"file into an array?

    I need to manipulate the sound file directly using DSP, the first step is to read sampled data from "*.au" file into an array. How can I do that? Thanks a lot!!

    There is a file I/O tutorial in the Java Tutorial (google for Java Tutorial). You can read an .au file as bytes like any binary file.
    Or if you are using the Java Sound API, google for java sound api or java audio tutorial etc etc.

  • Getting file into an array of byte..

    Hi guys,
    i first thank you for all the help you've given in my precedent posts.
    Now i've to ask you a question.
    I need to convert some lines of a txt file(obtained from an excel table) into an array of byte in the best possible manner.
    My file can have a various number of rows and columns.
    With this code
    BufferedReader br = new BufferedReader(new InputStreamReader(myFile.getInputStream()));
    String line = null;
            while ((line = br.readLine()) != null) {
                    line = line.replace (',', '.');
                    StringTokenizer st = new StringTokenizer(line);
                    numberOfNumericColumns = (st.countTokens()-1);
                    col=(numberOfNumericColumns+1);I read the file, i change , with . and line to line i calculate the number of value(that have to be the same,i do the control for showing exception if necessary).
    Now i know from my file what are the number of values in a row(columns of my old excel table).
    I have to convert this file into an array of byte.
    How can i do it?
    Suppose we have only 3 lines, the first line is ever only string,the others lines have a string and other double values.....
    nome giuseppe carmine paolo
    valerio 23.3 34.3 43.3
    paolo 21.2 34.5 12.2
    each value is separated from another one by one or more whitespaces..
    The most important thing is that in a second moment i have to read this array of byte and showing its original content,so i have to put in the array some different value and different line symbol delimiter.
    Can you help me giving me some idea or code?(please be clear,i'm inexpert of java...)
    Thanks very much,i need your help
    Message was edited by:
    giubat

    thanks for your reply...
    my file has about 50000 rows..........and i have to develop an application that allows the upload of about 6000/7000 files....
    so i have to optimize everythings......i want to use whitespace to separate different value and ;different line
    so in my array of bytes i want
    nome(converted in byte) whitespace(in byte) giuseppe (in byte) whitespace(in byte)carmine(in byte) whitespace(in byte) paolo (in byte) ;(in byte);
    valerio(in byte) whitespace(in byte) 23.3 (in byte) whitespace(in byte) 34.3 (in byte) whitespace(in byte)43.3 (in byte) ;(in byte) etc.....So i should have an array of byte lower than the array of byte obtained converting each line as a string into bytes.......
    do you understand what's my problem?
    How can i create an array of byte without fixing its initial dimension that is able to grows up for each line read?
    Excuse for my poor english..
    In the past i've used a vector to temporary store the data while reading the file and at the end i copied the vector in the array of byte but when i do upload in my application i had java heap size error.
    So someone has suggested me to improve my storing method and i've decided to eliminate vector....
    can you help me......????
    please....i need your help..

  • Get the content of a file into a array

    Hy to all!I have txt file with the following content : 0 1 1 0
    1 1 1 0
    0 0 0 0. I want to extract the values to a bi-dimension array,like this: a[0][0] = 0,a[0][1] = 1,a[0][2] = 1....and so on.
    Anybody could give a little help.THX

    The first thing I can help you with is that this doesn't have anything to do with java serialization.
    Secondly, if you are new to java, the best forum is "New To Java" forum.
    Thirdly, make sure you have done a google search first for an answer because it is likely that many people have asked the same question before.
    The follow search gets over 2 million hits. [http://www.google.co.uk/search?q=java+read+content+of+a+file+into+a+array]

  • How do I read directly from file into byte array

    I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
    try
                //Read File Contents into a Buffered Image
                /** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
                 * (at least partially) a problem with non-standard colour models, which is why we set the
                 * destination colour model. The side effect should be standard colour model in subsequent reading.
                BufferedImage bi = null;
                ImageReader ir = null;
                ImageInputStream stream =  ImageIO.createImageInputStream(new File(path));
                final Iterator i = ImageIO.getImageReaders(stream);
                if (i.hasNext())
                    ir = (ImageReader) i.next();
                    ir.setInput(stream);
                    ImageReadParam param = ir.getDefaultReadParam();
                    ImageTypeSpecifier typeToUse = null;
                    for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
                        ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
                        if (type.getColorModel().getColorSpace().isCS_sRGB())
                            typeToUse = type;
                    if (typeToUse != null)
                        param.setDestinationType(typeToUse);
                    bi = ir.read(0, param);
                    //ir.dispose(); seem to reference this in write
                    //stream.close();
                //Write Buffered Image to Byte ArrayOutput Stream
                if (bi != null)
                    //Convert to byte array
                    final ByteArrayOutputStream output = new ByteArrayOutputStream();
                    //Try and find corresponding writer for reader but if not possible
                    //we use JPG (which is always installed) instead.
                    final ImageWriter iw = ImageIO.getImageWriter(ir);
                    if (iw != null)
                        if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Unable to Write Image");
                    else
                        if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
                    //Add to image list
                    final byte[] imageData = output.toByteArray();
                    Images.addImage(imageData);
                  

    If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.

  • Reading .txt file into char array, file not found error. (Basic IO)

    Iv been having some trouble with reading characters from a text file into a char array. I havnt been learning io for very long but i think im getting the hang of it. Reading and writing raw bytes
    and things like that. But i wanted to try using java.io.FileReader to read characters for a change and im having problems with file not found errors. here is the code.
    try
    File theFile = new File("Mr.DocumentReadMe.txt");
    String path = theFile.getCanonicalPath();
    FileReader readMe = new FileReader(path);
    char buffer[] = new char[(int)theFile.length()];
    int readData = 0;
    while(readData != -1)
    readData = readMe.read(buffer);
    jEditorPane1.setText(String.valueOf(buffer));
    catch(Exception e)
    JOptionPane.showMessageDialog(null, e,
    "Error!", JOptionPane.ERROR_MESSAGE);
    The error is: java.io.FileNotFoundException: C:\Users\Kaylan\Documents\NetBeansProjects\Mr.Document\dist\Mr.DocumentReadMe.txt (The system cannot find the file specified)
    The text file is saved in the projects dist folder. I have tried saving it elsewhere and get the same error with a different pathname.
    I can use JFileChooser to get a file and read it into a char array with no problem, why doesnt it work when i specify the path manually in the code?

    Well the file clearly isn't there. Maybe it has a .txt.txt extensionthat Windows is kindly hiding from you - check its Properties.
    But:
    String path = theFile.getCanonicalPath();
    FileReader readMe = new FileReader(path);You don't need all that. Just:
    FileReader readMe = new FileReader(theFile);And:
    char buffer[] = new char[(int)theFile.length()];You don't need a buffer the size of the file, this is bad practice. Use 8192 or whatever.
    while(readData != -1)
    readData = readMe.read(buffer);
    }That doesn't make sense. Read the data into the buffer and repeat until you get EOF? and do nothing with the contents of the buffer? The canonical read loop in Java goes like this:
    while ((count = in.read(buffer)) > 0)
      out.write(buffer, 0, count); // or do something else with buffer[0..count-1].
    jEditorPane1.setText(String.valueOf(buffer));Bzzt. That won't give you the content of 'buffer'. Use new String(buffer, 0, count) at least.

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

  • Read very very large excel file into 2d array (strings or varient)

    Hi all,
    Long time user, first time poster on these boards.
    Looking at the copius amounts of great info related to reading Excel data from .xls files into labview, i've found that every one i've found from various people use the ActiveX method (WorkSheet.Range) which two strings are passed, namely excel's LetterNumber format to specify start and end.
    However, this function does not work when trying to query huge amounts of information. The error returned is "Type Mismatch, -2147352571" I have a very large excel sheet i need to read data from and then close the excel file (original file remains unchanged). However this file is gigantic (don't ask me, I didn't make it and I can't convince them to use something more appropriate) with over 165 columns at 1000 rows of data.I can read a large number of columns, but only a handful of rows, or vice versa.
    Aside from creating a loop to open and close the excel file over and
    over reading pieces of it at a time, is there a better way to read more
    data using ActiveX? Attached is code uploaded by others (with very minor modification) as an example.
    Thanks,
    Attachments:
    Excel Get Data Specified Field (1-46col).vi ‏23 KB

    Hi Maddox731,
    I've only had a very quick glance through your thread, and I must admit I haven't really thought it through properly yet. Sounds like you've come up with your own solution anyway. That said I thought I'd take a bit of a scatter gun approach and attach some stuff for you regradless. Please forgive my bluntness.
    You'll find my ActiveX Excel worksheet reader, which may or may not contain the problem you've come across. I've never tried it with the data size you are dealing with, so no promises. I've also attached my ADO/SQL approach to the problem. This was something I moved onto when I realised the limitations of AX. One thing I have noticed is that ADO/SQL is much faster than AX, so there may be some gains for you there with large data sets if you can implement it.
    I should add that I'm a novice to all this and my efforts are down to bits I've gleamed from MSDN and others' LV examples. I hope it's of some use, if only to spark discussion. Your ctiticism is more than welcome, good or bad.
    Regards.
    Attachments:
    Database Table Reading Stuff.zip ‏119 KB

  • How do I convert an image file into an array?

    I am using LabVIEW v.6.0.2
    I have no NI IMAQ device or IMAQ card, also no Vision
    The image file I have can be saved as a file containing numbers relating to the picels. I want to put these numbers into an array and plot a cross section intensity chart ( I am investigating young's double slits experiment and want to see the interference fringes in graphical form).

    I'm not sure what you're asking.
    In the GRAPHICS palette, there are READ JPEG file, READ BMP file, and READ PNG file VIs. Choose one and together with DRAW FLATTENED PIXMAP and a PICTURE indicator, you can display a picture with two functions and two wires.
    If you have spreadsheet-type data and import it with READ FROM SPREADSHEET FILE (in the File I/O palette), you can plot that directly to an intensity indicator.
    Steve Bird
    Culverson Software - Elegant software that is a pleasure to use.
    Culverson.com
    Blog for (mostly LabVIEW) programmers: Tips And Tricks

  • Loading a map + variables "drawn" in a txt file into an array

    hey guys, somewhat new to java, i have an assignment for school that requires me to create an "AI" that can solve a maze, easy enough. I used a 2 dimensional array for the maze, where 1 = wall, 0 = path, 3 = visited. etc, as far as the navigating goes, it's all done. The problem: i need to be able to load a maze from a file, the file looks like this:
    7 20 <-- rows/columns
    0 10 <------ start
    6 5 <---- finish
    xxxxxxxxxx  xxxxxxxxxx
    x        x            xxx      x
    x   xxxxxx      xxx     xxx
    x  xxxxxxx  xxxx  xxxxxx
    x  x            xx           xxx
    x xx     xxxxxxx  xx       x
    xxxxxoxxxxxxxxxxxxxxxSo basically i need to store the first numbers in variables so i know what size array to create and where to start solving the maze and then i somehow need to figure out a way to transofrm that drawing into an array. Was looking into parsing the text and trying to use tokens to separate it, but i honestly can't figure out how. If someone can drop a few hints or some functions i can use, i'd much appreciate it!

    Read the Java Doc API for
    FileReader
    BufferedReader
    String.split
    String.toCharArray

  • Converting a text file into an array

    import java.io.*;
    public class Copy {
    public static void main(String[] args) throws IOException {
         File inputFile = new File("farrago.txt");
         File outputFile = new File("outagain.txt");
    FileReader in = new FileReader(inputFile);
    FileWriter out = new FileWriter(outputFile);
    int c;
    while ((c = in.read()) != -1)
    out.write(c);
    in.close();
    out.close();
    i have been working my way through the online tutorials and have found them very helpful, i have looked at array and would like to know how to convert data from a text file inot an array? using the above example how would i go about doing this?

    You'd use the readLine () method:BufferedReader reader = new BufferedReader (new FileReader (file));
    String line;
    List list = new LinkedList ();
    while ((line = reader.readLine ()) != null) {
        list.add (line);
    // don't know why you'd want this, but anyway
    String[] lines = (String[]) list.toArray (new String[list.size ()]);Kind regards,
      Levi

  • Unable to read images into an array

    Hi there,
    I hope that someone will be able to help me. I have set up a program that will set the loop count to the number of images in the folder (orange input). With each execution of the loop, I would like an image to be read from file (using IMAQ ReadFile) and then stored to an array (purple output). Please find the screenshot attached with a snip of the code in question and the error that results from executing the vi (highlights the IMAQ ReadFile vi).
    I do have 5 images with the name: image0.png - image4.png in the folder directory specified by "Image Read File Path" and made sure that the path appends the actual name to the file path.
    I am fairly new to Labview programming (I have searched for a solution and troubleshooted as much as I can) and I hope I have provided enough information.
    Kind regards,
    Richard
    Attachments:
    Program.PNG ‏19 KB

    I wonder if the extra backslash is messing up the path. "Build Path" handles the file seperator. Right click on the final path and select Probe, or create and indicator to see the path.
    Attachments:
    Untitled.png ‏3 KB

Maybe you are looking for

  • How to get a value from php after some seconds?

    Hello, Does someone know how to do the following thing? I want to read a value from a php file with this method : request.method = URLRequestMethod.POST; But when you do this, the php file is excecuted and the variables will be read. But what if you

  • Displaying text more than 256 in ALV report

    Hi experts,                  I have problem while displaying text field in ALV report which has more than 256 characters. I'm using CL_SALV_TABLE for displaying alv.while concatenating my internal table holding all the text.but at the time of displyi

  • Getting next calendar event on home screen

    I have just bought an iPhone 5, never had one before. On my old htc and before that, on my Nokia n95, I could get the next calendar event on my home screen - how do I do this on my iPhone?

  • Convert to JTable, validation, more

    Hello everyone, I'm currently doing my project and a bit short of time. I'm a really bad programmer and struggling with this. There are some things I need help with and would really appreciate your assistance. Here is my program right now, it's not c

  • Problem in adding "Reason for Rejection" using BAPI_SALESORDER_CHANGE

    Hi all,        I have a requirement to stop further processing of sales order by changing the reason for rejection at line item. I have done the code and passed the reason code in the item table to BAPI. The return message says the sales order ammend