Converting string from file to array

I'm new to LabVIEW and have been thrown into the middle of a project, so I need to get some code working fast! Can someone help me understand why the VI I've attached isn't working? I want to have a text file that contains a list of integers that will be used to reference particular elements in arrays within my program. I tried to follow an example I found, but the output that should be an array is coming out as a scaler. Any help would be super appreciated! Thanks!
Solved!
Go to Solution.
Attachments:
string_to_array.vi ‏9 KB
exp.txt ‏1 KB

First, let's explain the reason for your error: The reason why it's happening is that you're trying to do two different things at the same time. You're auto-indexing the array and you're trying to index the array inside the loop. When you wire an array to a for loop it auto-indexes the loop. Meaning LabVIEW knows how many times to run the loop - there is no need to wire to the N terminal. Also, the wire inside the loop will be an instance of the element of the array, not the array. So, the wire inside the loop is a scalar. Thus, the reason for the broken wire - you can't index a scalar.
Also, I'm not sure what you're trying to do with the indexing of the one element of the cluster. The cluster is empty, so there's nothing to index. Presumably the file is there to tell you which elements to pull out from the "Amp2" array from the cluster. If so, remember that auto-indexing works both ways. If you connect an "outbound" wire to the edge of a loop it auto-indexed there as well, meaning the output will be an array.
Please read the LabVIEW Help on auto-indexing.
Now, given all of that, here is what your code should look like:
Note the use of the Read From Spreadsheet File VI. It makes your life easier.
Attachments:
fixed code.png ‏22 KB

Similar Messages

  • Get specific Strings from File

    Good morning to every one.
    I 've got a text file which contains a customer number and an order number, coded as we see in the picture below:
    I am trying to develop a tool in Visual Studio, which it reads the file line-by-line and fills a listbox, with the order_number and the customer number. From the file above, I know that the order number are the digits on the first 'column' after the leading-zeros,
    until '/', and the customer number are the digits without zeros in the 'third' column before 'CUSTOMER_NUMBER'. My form looks like:
    The problem is, that the number of before the fields in file, are not equal in every line.
    So, my question is how I can retrieve the 'order number' and 'customer number' from the text file and copy the results to list box, after clicking on 'Get Strings' button, like:
    359962656   2238914
    359562804   2238914
    etc...
    I attach my code here:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    namespace ReadStringFileApp
    public partial class frmMain : Form
    public frmMain()
    InitializeComponent();
    OpenFileDialog openfile = new OpenFileDialog();
    //openfiledialog to pickup filename
    private void btnFindFile_Click(object sender, EventArgs e)
    openfile.Filter = "Text|*.txt";
    if (openfile.ShowDialog() == DialogResult.OK)
    lbxResults.Items.Clear();
    txtFilepath.Text = openfile.FileName.ToString();
    //get strings from file
    private void btnGetStrings_Click(object sender, EventArgs e)
    //check if there is a file path on textbox
    if (txtFilepath.Text == "")
    MessageBox.Show("No File Select. Please select a file", "Error File Name", MessageBoxButtons.OK, MessageBoxIcon.Error);
    btnFindFile.Focus();
    return;
    //create list for all lines inside file
    List<string> lines = new List<string>();
    string line;
    using (StreamReader r = new StreamReader(@txtFilepath.Text))
    while ((line = r.ReadLine()) != null)
    string ordernum;//string for order number
    string customer;//string for customer number
    //line = ordernum + "\t" + customer; //concatenate results to fill the list box
    lbxResults.Items.Add(line);
    r.Close(); //close file
    private void btnExportToFIle_Click(object sender, EventArgs e)
    //check if listbox is empty
    if (lbxResults.Items.Count == 0)
    MessageBox.Show("Result List is empty! Choose a file to proceed.", "Error Result List", MessageBoxButtons.OK, MessageBoxIcon.Error);
    btnGetStrings.Focus();
    return;
    //read listbox contents and parse to a list object
    List<string> list = new List<string>();
    foreach (String i in lbxResults.Items)
    list.Add(i);
    //Create a file in c: with results
    File.WriteAllLines(@"C:\export-test.txt", list, Encoding.Default);
    MessageBox.Show("File export completed!", "File Export", MessageBoxButtons.OK, MessageBoxIcon.Information);
    Thank you in advanced

    @ Joel Engineer
    and@
    Val10
    I combined your responses and I get my results correctly. I attached the code I rewrite for further use:
    private void btnGetStrings_Click(object sender, EventArgs e)
    //check if there is a file path on textbox
    if (txtFilepath.Text == "")
    MessageBox.Show("No File Select. Please select a file", "Error File Name", MessageBoxButtons.OK, MessageBoxIcon.Error);
    btnFindFile.Focus();
    return;
    //create list for all lines inside file
    List<string> lines = new List<string>();
    string line;
    using (StreamReader r = new StreamReader(@txtFilepath.Text))
    while ((line = r.ReadLine()) != null)
    string order_customer;
    Regex reg = new Regex("0*");
    //set an string array, to split the file in columns positions, defining the characters
    string[] daneio = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
    //get order number from the first column
    var ordernum_zeros = reg.Match(daneio[0]).Value;
    daneio[0] = daneio[0].Replace(ordernum_zeros, String.Empty);
    daneio[0] = daneio[0].Substring(0, daneio[0].IndexOf("/"));
    //get customer column, without zeros
    var customer_zeros = reg.Match(daneio[5]).Value;
    daneio[2] = daneio[2].Replace(customer_zeros, String.Empty);
    daneio[2] = daneio[2].Substring(0, daneio[5].IndexOf("CUSTOMER_NUMBER"));
    //combine the result in listbox
    order_customer = daneio[0] + "\t" + daneio[2];
    lbxResults.Items.Add(order_customer);
    r.Close(); //close file
    Thank you for your help!

  • Convert String from ASCII to ANSI

    Hi,
    a command line instruction via LabVIEW function "System Exec.vi" retrieves me a string in ASCII format. Is there a function to convert string from ASCII to ANSII format? I use LabVIEW 8.5 German Installation.
    Kind Regards
    Christian
    Test Engineering
    digades GmbH
    www.digades.com

    Hallo Christian,
    AFAIK there is no such in function in LabView...
    But you can:
    - use "Search and replace string" to search for ASCII chars and replace them by their corresponding ANSI char, do this in a loop for all chars to be replaced (acceptable speed for small strings...)
    - convert the string to an U8 array and use a lookup table to convert all bytes from ASCII to ANSI, convert back to string (may be faster for long strings...)
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Getting data from file to array

    try
        System.out.println("Enter file name: ");
        fileName = Object.nextLine();
        BufferedReader inputStream =
                new BufferedReader(new FileReader(fileName));
        String employee = null;
        employee = inputStream.readLine();
        System.out.println("The first employee in " + fileName + " is");
        System.out.println(employee);
        inputStream.close();
    catch(FileNotFoundException e)
        System.out.println("File " + fileName + " not found ");
    catch(IOException e)
        System.out.println("Error reading from file " + fileName);
    }This is just a little example I made. You can look at my other thread to see the other code. I need to put the data in a file into the array. Does it need to be casted somehow?

    public void getData()
           try {
       System.out.println("Enter file name to read: ");
       File = Object.nextLine();
       BufferedReader Object =
                new BufferedReader(new FileReader(File));
        for(int i = 0; i < people.length && people[i] != null; i++)
    String temp = Object.readLine();
    people.setLastname(temp);
    temp = Object.readLine();
    people[i].setFirstname(temp);
    temp = Object.readLine();
    people[i].setID(temp);
    temp = Object.readLine();
    people[i].setPhone(temp);
    temp = Object.readLine();
    people[i].setYearlySalary(Double.parseDouble(temp));
    temp = Object.readLine();
    people[i].calcBonus(Double.parseDouble(temp));
    temp = Object.readLine();
    people[i].getMonthlyPay(temp));
    } Object.close(); }I know, I got careless with the naming. I'm trying a different route now. I think I can just do it in reverse. lol How would I get the method getMonthlyPay to have no errors. It's a public void() method with monthlyPay = (yearlySalary + bonus) / 12; in its definition.
    anyone?
    Edited by: Program_1 on Dec 9, 2007 5:42 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Convert String from UTF-8 to IsoLatin1

    Hi everyone !
    I'm trying to convert a String from utf-8 to IsoLatin1, but i got somt problems.... I'm using
    actually this code, but it won't work...
    I'm getting a utf-8 html String with some data and i will write it down in latin1 to a text file
    String newString = new String(oldString.getBytes("UTF-8"), "ISO-8859-1");If i'm now writing this newString to a TextFile it contains cryptic signs like
    & # 1 3 ; or & # 1 3 7 ; or & # 1 2 8 ;(i separated this chars)
    can anyone tell me where is my fault and how can i solve this problem ?
    Thanks a lot
    Edited by: Sephiknight on Feb 23, 2008 2:41 AM

    Yes its XML, i got a web editor where i can add input (utf-8) and i want to write it down in my class to a xml file (isoLatin1).
    My code looks likte this
         public static void setEditFragment(String content, String xPath) throws Exception {
             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
             DocumentBuilder builder  = factory.newDocumentBuilder();
             Document document = builder.parse("3001300.xml");
             XPath xpath = XPathFactory.newInstance().newXPath();
             Node node = (Node)xpath.evaluate(xPath, document, XPathConstants.NODE);
            Charset charset = Charset.forName("ISO-8859-1");
            CharsetEncoder encoder = charset.newEncoder();    
            ByteBuffer buf = encoder.encode(CharBuffer.wrap(content));
            node.setTextContent(buf.toString()); 
               // Use a XSLT transformer for writing the new XML file
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
             DOMSource        source = new DOMSource( document );
             FileOutputStream os     = new FileOutputStream("tmp.xml");
             StreamResult     result = new StreamResult( os );
             transformer.transform( source, result ); 
         }The example from http://www.exampledepot.com/egs/java.nio.charset/ConvertChar.html looks great, but if I add my own input string i get a exception that looks like this
    java.nio.charset.UnmappableCharacterException: Input length = 1
         at java.nio.charset.CoderResult.throwException(Unknown Source)
         at java.nio.charset.CharsetEncoder.encode(Unknown Source)
         at HagerAbs.setEditFragment(HagerAbs.java:91)
         at HagerAbs.main(HagerAbs.java:108)When i write my input to the xml file it doesnt look like xml at all, it looks more like
    <synthese>& # 13;
    & # 13;
    & lt;br/& gt;& # 13;
    & lt;img class="thumb" src="http: ......{code}
    (i seperated the char so you can see)
    and this is not what i expected... how can i write it down correctly ?
    Edited by: Sephiknight on Feb 23, 2008 3:26 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

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

  • How to read a string from file & assign the val to a variable in batch file

    Hi,
    How to read a string from a file and assign the value to a variable then return the value to the screen in windows batch file?
    Any suggestions?
    thanks.

    Unless this is a homework question then I don't see the purpose of doing this, but....
    You should be looking a the supplied package utl_file to get the string out of the file, dbms_output to display the string and then google windows batch/command files calling sqlplus to execute your program.
    Andre

  • Help with deleting multiple strings from file.......

    I am trying to delete the same string that may appear multiple times in the file. Here is the output to the screen. Here is the code. I have been researching the delete method it says that I have to start at an index position in the string but how would I find out where the multiples strings reside in the file? I am getting the feeling that it won't work for my purpose..???? I am trying to delete all ot the strings "a string of data3" from the file.
    Output
    C:\TestRead>java StringDelete
    Temp String file_data-------- a string of data3a string of data2a string of data
    1a string of data3a string of data2a string of data1a string of data3
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data3
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data2
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data1
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data3
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data2
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data1
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data3
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    Code:
    import java.io.*;
    public class StringDelete
    public static void main(String [] args)
    try
    FileInputStream fis = new FileInputStream("TestFile.txt");
    DataInputStream in = new DataInputStream(fis);
    StringBuffer file_data = new StringBuffer();
    while(in.available() > 0)
    String temp = in.readUTF(); // read in a string from the file
    file_data.append(temp); // append it to the buffer
    System.out.println("Temp String file_data-------- " + file_data);
    System.out.println("Just A Blank Line");
    System.out.println("Just A Blank Line");
    System.out.println("Just A Blank Line");
    boolean keepGoing = true;
    while(keepGoing)
    String toDelete = file_data.substring(0, "a string of data3".length());
    System.out.println("String toDelete-------- " + toDelete);
    System.out.println("Just A Blank Line");
    System.out.println("Just A Blank Line");
    System.out.println("Just A Blank Line");
    if(toDelete == null || toDelete.equals("") )
    keepGoing = false;
    else
    file_data.delete(0,"a string of data3".length());
    catch(IOException e)
    e.printStackTrace();

    Here is the output. I am trying to get each part to work before I go on to the next part that is why some code is commented out.
    I need help to know why string "a string of data3" is not deleted in the towrite string??
    Output:
    C:\TestRead>java NewStringDelete
    String v after remove [ &#9668;a string of data3 &#9668;a string of data2 &#9668;a string of data1
    &#9668;a string of data3 &#9668;a string of data2 &#9668;a string of data1 &#9668;a string of data3]
    String towrite after remove &#9668;a string of data3 &#9668;a string of data2 &#9668;a string of
    data1 &#9668;a string of data3 &#9668;a string of data2 &#9668;a string of data1 &#9668;a string of data
    3
    Code:
    import java.util.Vector;
    import java.io.*;
    public class NewStringDelete
         public static void main(String [] args)
              //String ls = System.getProperty("line.separator");
              //File file;
              Vector v=new Vector();
         try{
              BufferedReader br=new BufferedReader(new FileReader ("TestFile.txt"));
              String s;
              while ((s=br.readLine())!=null)
                   {v.addElement(new String(""+s));}
                        br.close();
         catch(IOException e)
                   e.printStackTrace();
    /*now you have a Vector containing String objects..*/
         String remove = ("a string of data3");
         String towrite="";
    System.out.println("String v after remove " + v);     
         for (int i=0; i<v.size();i++)
              String ss = (String)v.elementAt(i);
              if (ss.equalsIgnoreCase(remove)){continue;}
              //     towrite=towrite+ss+ls;
                   towrite=towrite+ss;
    System.out.println("");               
    System.out.println("");               
    System.out.println("String towrite after remove " + towrite);                    
    /*do filewrite*/
    //try{
    // FileWriter fw=new FileWriter(TestFile.txt);
    // fw.write(towrite);
    // fw.close();
    // catch(IOException e)
    //               e.printStackTrace();

  • Assigning a number value to a line from file without array

    How do you assign a number value to a line from a file? I want to use the assigned number so that the i can use random number to randomly select a line
    Example. i have the lines A,B,C,D,E
    A
    B
    C
    D
    E
    i know that a is line 1 b is line 2 so on so on
    (1) A
    (2)B
    (3)C
    (4)D
    (5)E
    so from here i would use the random number generator so that i could randomly select one of these. I already know how to code for the number generator but how would i make it so that i can access each individual line as a number?

    ya that's what im using but reguarding the code i dont think it does what im looking for. yes it does provide a random line but wen i run it multiple times it gives me the same line repeatedly. also i need to be able to refer to that line in the future so in the code the String line gets replaced each time
    BufferedReader bF = new BufferedReader(new FileReader("someFilePath"));
              String line;
              int someRandomNumber = 9;
              int counter = 0;
              while ((line = bF.readLine()) != null){
                   if (counter == someRandomNumber){
                        break;
                   counter++;          
              System.out.println(line); //line at #someRandomNumber in the file

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

  • I want to convert string to 1-D array to input it to waveform graph?

    thanks in advance

    Hi oiuuhjoi,
    ok, and where's the problem?
    Spoiler (Highlight to read)
    Ever tried SpreadsheetStringToArray?
    Ever tried SpreadsheetStringToArray?
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Find and replace string in file

    hi,
    i need to find and replace text (string) data in about 100+ files, i've decided to write a small java program to do it but i'm stuck on how to replace.
    here is what i'm heading towards:
    class ReplaceString {
      BufferedReader in;
      BufferedReader os;
      public static void main(String args[]) {
        ReplaceString obj = new ReplaceString();
        obj.replace();
       void replace() {
         try {
           in = new BufferedReader(new FileReader("a.txt");
           os = new BufferdWriter(new FileWriter("a.txt");
           //  read until end of file
           String currentLine = new String();
           while((currenLine=is.readLine()) != null) {
             //  if matching text then replace????
             if(currentLine.equals("Version 001") {
                // how to now replace the Version 001 with Version 002???
         }catch(IOException e) {
            System.out.println(e);
            in.close();
            os.close();
         in.close();
         os.close();
    }the above code i just typed so there might be errors, but looks ok to me, is there any way once i find the string i want to replace, to replace the string with another string. basically i want to replace all occurrences of the text "Version 001" with "Version 002"
    Thank you.

    Is it always true, as in your example, that the replacement is the same length as the existing string? If so, this one's easy.
    Is it also true that you don't need to worry about 16-bit chars? (Again, as in your example.) If you're using just ASCII characters, this gets easier still.
    1) Segregate the file I/O from the search/replace process.
    2) Main becomes:
    readFile();
    replace( "this", "that" );
    writeFile();Use a byte array buffer, defined in your main class. Fill it via the readFile() code. Use a RandomAccessFile, check its length() to allocate your byte array, then do a single read() to fill the buffer.
    A brute force search will certainly work: scan for the first search character, then check the rest for a match, replace if you've got a match and continue scanning. Alternative if your file's aren't too big: create a String from the byte array:
    // buffer is a byte array
    String s = new String( buffer );And use the String.replaceAll() to do the search/replace. Recover the buffer with:
    buffer = string.getBytes();A single write() and close() should handle the remaining work.

  • An array of strings from a file?

    I have a file with 2000 names and want to make an array of type string................
    When i compile and run all all i get is null values in my array?
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Scanner;
    import java.io.IOException;
    public class Names
              private String name;
              private String surname;
              PrintWriter output = null;
              String[] LastName = new String[2000]; //set up array of first names
              String[] Name = new String[2000];; //set up array of first names
         public void setSurname(String suname)
              this.surname=suname;
         public String getSurname()
              return surname;
         public void loadFromFile(String fname) //method loads form text file
              File file = new File("SURNAMES.txt");
              Scanner in = null;
              try {
                    in = new Scanner(file);
                     catch (FileNotFoundException fnfe)
                        System.out.println("File not found");
                    int x=0;
                    while(in.hasNextLine())
                      surname = in.next();
                        LastName [x] = new String(surname);
                      x++;
                   in.close();
    public void test()
              for (int i = 0; i < 44; i++)
              System.out.println(LastName);
    Can anyone see why its not reading?

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import java.io.PrintWriter;
    public class ResultPredictor
         public static void main (String args[])
              Names play = new Names();
              //display menu to user & process user choice
              Scanner input = new Scanner(System.in);
              int choice = 0;
              while(choice!=4)
                   System.out.println("__________________________________________________________");
                   System.out.println("");
                   System.out.println("[1] Join the names");
                   System.out.println("[2] Display names that both name start with the same letter");
                   System.out.println("[3] Search for names starting with a letter");
                   System.out.println("[4] Exit");
                   System.out.println("");
                   System.out.print("What is your choice? ");
                   System.out.flush();
                   //check and process an integer choice
                   if (input.hasNextInt())
                        choice=input.nextInt();
                        switch(choice)
                                  case 1:
                                       play.test();
                                       break;
                                  case 2:
                                       break;
                                  case 3:
                                       break;
                                  case 4:
                                       System.out.println("\nGOODBYE!!\n\n");
                                       break;
                                  default:
                                       System.out.println("Please enter a valid menu option (1-4)");
                                       System.out.println("");
                                       break;
                   else //choice was not an integer
                        System.out.println("Please enter a valid menu option (1-4)");
                        input.next(); //move on
              }//end loop
         }// end main
    }when i run the code it returns null values, the SURNAMES.txt file is in the same folder. Could it be the way the files is delimited, its like so.........
    a
    b
    c
    d
    e
    f
    g
    and so on....

  • 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

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

Maybe you are looking for