How do I put and sort string data into an array?

I have a txt file that has the following sample data:
Sample.txt----
Jones Bill 12,500 Salesperson
Adams Frank 34,980 Manager
Adams John 23,000 Salesperson
Thompson Joe 59,500 Trainee
I need to incorporate each line of data into an individual array element, while using a user-defined method
(ex. setAllValues(String last, String first, String salary, String job)
How do I loop the data into the array to be displayed and what is the best way to do sorts on this sample data. Any code or clues would be super helpful.
Sanctos

If you set up an array of Strings you can use the java.util.Arrays.sort() method to sort it. If you need to sort arbitrary Objects (i.e. your 3 strings as a whole entity) your 3-way object will have to either implement Comparable or you could write a Comparitor class to do the ordering. Not much to it, though.
Dom.

Similar Messages

  • (Urgent help needed) how to read txt file and store the data into 2D-array?

    Hi, I have a GUI which allow to choose file from the file chooser, and when "Read file" button is pressed, I want to show the array data into the textarea.
    The sample data is like this followed:
    -0.0007     -0.0061     0.0006
    -0.0002     0.0203     0.0066
    0     0.2317     0.008
    0.0017     0.5957     0.0008
    0.0024     1.071     0.0029
    0.0439     1.4873     -0.0003
    I want my program to scan through and store these data into 2D array.
    However for some reason, my source code issues errors, and I don't know what's wrong with it, seems to have a problem in StringTokenizer though. Can anybody help me?
    Thanks in advance.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.StringTokenizer;
    public class FileReduction1 extends JFrame implements ActionListener{
    // GUI features
    private BufferedReader fileInput;
    private JTextArea textArea;
    private JButton openButton, readButton,processButton,saveButton;
    private JTextField textfield;
    private JPanel pnlfile;
    private JPanel buttonpnl;
    private JPanel buttonbar;
    // Other fields
    private File fileName;
    private String[][] data;
    private int numLines;
    public FileReduction1(String s) {
    super(s);
    // Content pane
         Container cp = getContentPane();
         cp.setLayout(new BorderLayout());     
    // Open button Panel
    pnlfile=new JPanel(new BorderLayout());
         textfield=new JTextField();
         openButton = new JButton("Open File");
    openButton.addActionListener(this);
    pnlfile.add(openButton,BorderLayout.WEST);
         pnlfile.add(textfield,BorderLayout.CENTER);
         readButton = new JButton("Read File");
    readButton.addActionListener(this);
         readButton.setEnabled(false);
    pnlfile.add(readButton,BorderLayout.EAST);
         cp.add(pnlfile, BorderLayout.NORTH);
         // Text area     
         textArea = new JTextArea(10, 100);
    cp.add(new JScrollPane(textArea),BorderLayout.CENTER);
    processButton = new JButton("Process");
    //processButton.addActionListener(this);
    saveButton=new JButton("Save into");
    //saveButton.addActionListener(this);
    buttonbar=new JPanel(new FlowLayout(FlowLayout.RIGHT));
    buttonpnl=new JPanel(new GridLayout(1,0));
    buttonpnl.add(processButton);
    buttonpnl.add(saveButton);
    buttonbar.add(buttonpnl);
    cp.add(buttonbar,BorderLayout.SOUTH);
    /* ACTION PERFORMED */
    public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals("Open File")) getFileName();
         if (event.getActionCommand().equals("Read File")) readFile();
    /* OPEN THE FILE */
    private void getFileName() {
    // Display file dialog so user can select file to open
         JFileChooser fileChooser = new JFileChooser();
         fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
         int result = fileChooser.showOpenDialog(this);
         // If cancel button selected return
         if (result == JFileChooser.CANCEL_OPTION) return;
    if (result == JFileChooser.APPROVE_OPTION)
         fileName = fileChooser.getSelectedFile();
    textfield.setText(fileName.getName());
         if (checkFileName()) {
         openButton.setEnabled(false);
         readButton.setEnabled(true);
         // Obtain selected file
    /* READ FILE */
    private void readFile() {
    // Disable read button
    readButton.setEnabled(false);
    // Dimension data structure
         getNumberOfLines();
         data = new String[numLines][];
         // Read file
         readTheFile();
         // Output to text area     
         textArea.setText(data[0][0] + "\n");
         for(int index=0;index < data.length;index++)
    for(int j=1;j<data[index].length;j++)
    textArea.append(data[index][j] + "\n");
         // Rnable open button
         openButton.setEnabled(true);
    /* GET NUMBER OF LINES */
    /* Get number of lines in file and prepare data structure. */
    private void getNumberOfLines() {
    int counter = 0;
         // Open the file
         openFile();
         // Loop through file incrementing counter
         try {
         String line = fileInput.readLine();
         while (line != null) {
         counter++;
              System.out.println("(" + counter + ") " + line);
    line = fileInput.readLine();
         numLines = counter;
    closeFile();
         catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error reading File",
                   "Error 5: ",JOptionPane.ERROR_MESSAGE);
         closeFile();
         System.exit(1);
    /* READ FILE */
    private void readTheFile() {
    // Open the file
    int row=0;
    int col=0;
         openFile();
    System.out.println("Read the file");     
         // Loop through file incrementing counter
         try {
    String line = fileInput.readLine();
         while (line != null)
    StringTokenizer st=new StringTokenizer(line);
    while(st.hasMoreTokens())
    data[row][col]=st.nextToken();
    System.out.println(data[row][col]);
    col++;
    row++;
    closeFile();
    catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error reading File",
                   "Error 5: ",JOptionPane.ERROR_MESSAGE);
         closeFile();
         System.exit(1);
    /* CHECK FILE NAME */
    /* Return flase if selected file is a directory, access is denied or is
    not a file name. */
    private boolean checkFileName() {
         if (fileName.exists()) {
         if (fileName.canRead()) {
              if (fileName.isFile()) return(true);
              else JOptionPane.showMessageDialog(null,
                        "ERROR 3: File is a directory");
         else JOptionPane.showMessageDialog(null,
                        "ERROR 2: Access denied");
         else JOptionPane.showMessageDialog(null,
                        "ERROR 1: No such file!");
         // Return
         return(false);
    /* FILE HANDLING UTILITIES */
    /* OPEN FILE */
    private void openFile() {
         try {
         // Open file
         FileReader file = new FileReader(fileName);
         fileInput = new BufferedReader(file);
         catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error Opening File",
                   "Error 4: ",JOptionPane.ERROR_MESSAGE);
    System.out.println("File opened");
    /* CLOSE FILE */
    private void closeFile() {
    if (fileInput != null) {
         try {
              fileInput.close();
         catch (IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error Opening File",
                   "Error 4: ",JOptionPane.ERROR_MESSAGE);
    System.out.println("File closed");
    /* MAIN METHOD */
    /* MAIN METHOD */
    public static void main(String[] args) throws IOException {
         // Create instance of class FileChooser
         FileReduction1 newFile = new FileReduction1("File Reduction Program");
         // Make window vissible
         newFile.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         newFile.setSize(500,400);
    newFile.setVisible(true);
    Java.lang.NullpointException
    at FileReductoin1.readTheFile <FileReduction1.java :172>
    at FileReductoin1.readFile <FileReduction1.java :110>
    at FileReductoin1.actionPerformed <FileReduction1.java :71>
    .

    1) Next time use the CODE tags. this is way too much unreadable crap.
    2) The problem is your String[][] data.... the only place I see you do anything approching initializing it is
    data = new String[numLines][];I think you want to do this..
    data = new String[numLines][3];anyway that's why it's blowing up on the line
    data[row][col]=st.nextToken();

  • How to put 58 columns of data into an array in one shot?

    I have a set of data with 58 columns and 5000 rows. However, I need to find offset for all the elements in this 5000x58 set of data. Is there an easier way to put all the data (offset) into an array in one shot other than using build array function? This is because if I use the build array function, I will need to separate all the data into 58 columns by indexing them. This is too time consuming.
    Thanks for the suggestion! Have a good day!

    VanessaWen wrote:
    I have a set of data with 58 columns and 5000 rows. However, I need to find offset for all the elements in this 5000x58 set of data. Is there an easier way to put all the data (offset) into an array in one shot other than using build array function? This is because if I use the build array function, I will need to separate all the data into 58 columns by indexing them. This is too time consuming.
    You need to explain in much more detail, because your problem is not clear.
    Is this a 2D array with 58 columns and 5000 rows?
    What is your definition of "offset"?
    Where does the offset value come from?
    Is "offset" it the same for each row (or column) or does it depend on the data?
    What is the definition of "one shot"?
    Why would you need to seperate all the data into columns in order to use build array?
    It it "too time consuming" to write the program or is the execution slower than expected?
    Is the final output a 1D or 2D array or something else?
    Please attach a VI containing a small 2D array diagram constant with typical data, then show us what kind of output you would expect after applying the described operation.
    LabVIEW Champion . Do more with less code and in less time .

  • How to import Filenames and File creation Date into Table..

    Hi Folks,
    I am importing Differennt Excels Files into table. my require ment is after importing completed I need to insert all these Filenames ,File creation date into table. (for Auditing).
    Can you please give me any ideas or reference link.  Thanks In Advance.

    Hi Folks,
    I am importing Differennt Excels Files into table. my require ment is after importing completed I need to insert all these Filenames ,File creation date into table. (for Auditing).
    Can you please give me any ideas or reference link.  Thanks In Advance.
    You can also prepare dir command and then exeucte it by using XP_CMDSHELL. This gives you file name, modified date, creation date information.
    Please refer:
    https://sqljourney.wordpress.com/2010/06/08/get-list-of-files-from-a-windows-directory-to-sql-server/
    https://hernandezpaul.wordpress.com/2013/02/15/store-file-names-and-modified-dates-in-a-table-without-a-foreach-loop-task-sql-server-ssis/
    Cheers,
    Vaibhav Chaudhari
    [MCP],
    [MCTS], [MCSA-SQL2012]

  • I-photo:  I used 2 cameras to take pictures on a trip --- i have put the pictures from both cameras into an album --- when i click on view and then sort by date, the pictures do not sort by date --- any ideas on how to get the pics sorted by date?

    I-photo:  I used 2 cameras to take pictures on a trip --- i have put the pictures from both cameras into an album --- when i click on view and then sort by date, the pictures do not sort by date --- any ideas on how to get the pics sorted by date?

    Select all the photos that you need to change, then click the "Photos" menu and choose "Adjust Date and Time".
    If you add a year, it will adjust all the photos that you selected by adding a year (so if you accidentally select one of the photos that already has "2012", that will change to "2013"). 

  • How to put data into a array element in the BPEL

    Hi,
    I have a element in the WSDL which is of type Array. (i.e accepts unlimited data for the same element). How should i put a data into a array in the BPEL.
    Example:
    The below Example gives u an idea about wht iam asking:pasting a piece of my requirement:
    <s:element minOccurs="0" maxOccurs="1" name="parameters" type="tns:ArrayOfCSParameters" />
    <s:complexType name="ArrayOfCSParameters">
    <s:sequence>
    <s:element minOccurs="0" maxOccurs="unbounded"
    name="CSParameters" nillable="true" type="tns:CSParameters" />
    </s:sequence>
    </s:complexType>
    <s:complexType name="CSParameters">
    <s:sequence>
    <s:element minOccurs="0" maxOccurs="1" name="RevenueItem" type="tns:RevenueItem" />
    <s:element minOccurs="0" maxOccurs="1" name="AccountURIs" type="tns:ArrayOfString" />
    <s:element minOccurs="0" maxOccurs="1" name="GroupURIs" type="tns:ArrayOfString" />
    <s:element minOccurs="1" maxOccurs="1" name="Percentage" nillable="true" type="s:decimal" />
    </s:sequence>
    <s:attribute name="Version" type="s:decimal" use="required" />
    <s:attribute name="URI" type="s:string" />
    </s:complexType>
    Any suggestion is appreciated.
    Regards
    pavan

    You have 2 options i guess.
    Use the transformation and the for-each to construct the array-list
    or like Richard said, use a loop in bpel, assign in the loop an variable of element type="CSParameters" and append this variable to your variable with accepts the arraylist.

  • HT4847 How do I put my iPhone stored items into my iCloud storage?i have bought an upgrade but none of my phones stored items have moved to iCloud.i can't download new update from apple. due to not enough and yet iCloud space is empty??please help thanks

    How do I put my iPhone stored items into my iCloud storage?i have bought an upgrade but none of my phones stored items have moved to iCloud.i can't download new update from apple. due to not enough and yet iCloud space is empty??please help I don't know what I doing all I know is my phone is iPhone 4 and I can't update it. My phone on contract with t-mobile . Thanks

    You can't have content in iCloud without having it on your phone, you will need to look at deleting items from your device that you don't need. Movies and TV shows from iTunes are possibly a good start because they tend to be large and can be redownloaded at a later date.

  • How can i open a DOC or TXT file and insert the data into table?

    How can i open a DOC or TXT file and insert the data into table?
    I have a doc file . the doc include some columns and some rows.(for example 'ID,Name,Date,...').
    I'd like open DOC file and I'd like insert them into the table with same columns.
    Thanks.

    Use the SQL*Loader utility or the UTL_FILE package.

  • How can I resize and reposition the Date Created window for All windows?

    When setting view options for a finder window set to list view, I cannot get column resizing or positioning to hold. When making those changes, the option for "All Windows" automatically shifts to "This window only" and it then does not hold.
    How can I resize and reposition the Date Created column for All WIndows?

    Hi Harmz,
    Try dragging this file to the Îesktop & reboot...
    /Users/YourUserName/Library/Preferences/com.apple.finder.plist

  • Hello! how can i put and read my words documents in the notes pad of my ipod nano 3trd generation?thanks to all.the notes

    hello! how can i put and read my words documents in the notes pad of my ipod nano 3trd generation?thanks to all.

    The Notes features of the 3G iPod Nano only supports TXT files and not Word Documents.  If you want to be able to read these word documents, you'll need to copy the text from each over to a text file.  See here for more information.
    iPod: Storing and reading notes
    Keep in mind that each txt file has a limit of 4096 characters.  See this article for more information as well.
    Long notes are truncated on your iPod
    B-rock

  • How to get Capacity And Custom Attribute Data Through Powershell

    how to get Capacity And Custom Attribute Data Through Powershell

    Hi Nitesh,
    Great command from Martin.
    Also find a article to configure the Quota:
    http://technet.microsoft.com/en-us/library/aa998353(v=exchg.141).aspx
    Thanks
    Mavis Huang
    TechNet Community Support

  • How can i save and retrieve blob data through forms and reports...

    I have blob data type column and I want to save word, html, gif
    document in oracle database through forms 6 and retrieve the
    data into forms and reports.
    Details : I want to open .doc,.html,.gif file through a button
    and save it ..and i want retrieve the data into text item same
    in reports....
    If anybody have the answer then send me at
    [email protected]

    use ole container
    initialize the container with the filename (doc or gif)
    Edited by: arshid on Feb 8, 2009 1:57 PM

  • Need help in putting data into 2d array

    My input file :
    1 , 2 , 1
    2 , 2 , 1
    3 , 3 , 1
    4 , 2 , 2
    2 , 3 , 2I'm stuck at:
    while( reader.readLine() != null){
    String Matrix[] = line.split(",");
    }Means I only can read how many lines there. For 2d array, Matrix[i][j], is that when I count the line, the number of count will be the 'i'? How about 'j'? Am I need to count i and j before put the data into 2d array?
    Do correct me if something wrong in:
    while( reader.readLine() != null){
    String Matrix[] = line.split(",");
    } Thank you.

    gtt0402 wrote:
    while( reader.readLine() != null){
    String Matrix[] = line.split(",");
    How about:
    ArrayList<String[]> rows = new ArrayList<String[]>();
    while((line = reader.readLine()) != null) {
        rows.add(line.split(","));
    }After the loop you have a list full of String arrays and you can convert it to a 2D String array if you wish.

  • How to insert more than 32k xml data into oracle clob column

    how to insert more than 32k xml data into oracle clob column.
    xml data is coming from java front end
    if we cannot use clob than what are the different options available

    Are you facing any issue with my code?
    String lateral size error will come when you try to insert the full xml in string format.
    public static boolean writeCLOBData(String tableName, String id, String columnName, String strContents) throws DataAccessException{
      boolean isUpdated = true;
      Connection connection = null;
      try {
      connection = ConnectionManager.getConnection ();
      //connection.setAutoCommit ( false );
      PreparedStatement PREPARE_STATEMENT = null;
      String sqlQuery = "UPDATE " + tableName + " SET " + columnName + "  = ?  WHERE ID =" + id;
      PREPARE_STATEMENT = connection.prepareStatement ( sqlQuery );
      // converting string to reader stream
      Reader reader = new StringReader ( strContents );
      PREPARE_STATEMENT.setClob ( 1, reader );
      // return false after updating the clob data to DB
      isUpdated = PREPARE_STATEMENT.execute ();
      PREPARE_STATEMENT.close ();
      } catch ( SQLException e ) {
      e.printStackTrace ();
      finally{
      return isUpdated;
    Try this JAVA code.

  • How do I put all my live feeds into one channel? I don't want to have to cick on each feed source separately.

    How do I put all my live feeds into one channel? I don't want to have to click on each feed source separately. Instead of one feed per website I want just ONE feed for all my sources together.

    Hi there old45,
    You may find the information in the article below helpful.
    iTunes 11 for Windows: Change where your iTunes files are stored
    http://support.apple.com/kb/PH12365
    Consolidate your files in the iTunes folder
    You can consolidate all the files in your library in the iTunes folder—for example, to make it easier to move your library to a new computer.
    Choose File > Library > Organize Library.
    Select “Consolidate files.”Files remain in their original locations, and copies are placed in the iTunes folder.
    To create folders (Music, Movies, TV Shows, Podcasts, Audiobooks, and so on) inside your iTunes folder, and place all your imported media files in the appropriate folders, select “Reorganize files in the folder ‘iTunes Media.’”
    Locate your iTunes files
    Do either of the following:
    Find out where a file is stored: Select the item in iTunes, and choose File > Get Info. The path to the file is shown at the bottom of the Summary pane (next to Where).
    Show the file in Windows Explorer: Select the song, and choose File > Show in Explorer.
    -Griff W.

Maybe you are looking for