Reading A String at a random location in a file

Question:
Given a file of English words (a dictionary file I guess�), delimited by commas, I want to know if it is possible to write a java program that can read a random word from the dictionary file and store it into a String.
If this is possible, I would like to know how to possibly implement such program.

Given a file of English words (a dictionary file I
guess�), delimited by commas, I want to know if it
is possible to write a java program that can read a
random word from the dictionary file and store it
into a String.One way is to scan the word file once and store the starting position of each word in a new file. Say you get N entries. To read a word randomly you first generate a random integer between 0 and N-1. You use that number to look up the corresponding word position in the first file. Using that you finally look up the actual word in the second file. (To speed things up if the first file isn't too big you can keep it in memory as an integer array).
The above procedure will give each word an equal chance of being selected.

Similar Messages

  • Reading an int from a particular location in a file

    Hi, I've seen other topics about reading ints from files/strings etc, but I don't think I've found one the same as this.
    I have an input file "maxSolution.sol" that contains an int that I need to use in my program
    c Parsing PB file...
    c Converting 0 PB-constraints to clauses...
    c -- Unit propagations: (none)
    c -- Detecting intervals from adjacent constraints: (none)
    c -- Clauses(.)/Splits(s): (none)
    c ==================================[MINISAT+]==================================
    c | Conflicts | Original | Learnt | Progress |
    c | | Clauses Literals | Max Clauses Literals LPC | |
    c ==============================================================================
    c | 0 | 0 0 | 0 0 0 nan | 0.000 % |
    c ==============================================================================
    c Found solution: -1
    c Optimal solution: -1
    s OPTIMUM FOUND
    v x0001 -x0101 -x0200 -x0201 -x0800
    c _______________________________________________________________________________
    c
    c restarts : 1
    c conflicts : 0 (nan /sec)
    c decisions : 2 (inf /sec)
    c propagations : 0 (nan /sec)
    c inspects : 0 (nan /sec)
    c CPU time : 0 s
    c _______________________________________________________________________________
    The int that I require is the one that appears after "Optimal Solution: ". I actually require the absolute value of this, so I have tried the following
    public int maxInputReader(String s) throws IOException
    String optimal = "Optimal Solution:";
    int mines = 0;
    File input = new File(s);
    Scanner filein = new Scanner(input);
    while(filein.hasNext())
    if(filein.next() == optimal)
    mines = Math.abs(Integer.parseInt(filein.next()));
    return mines;
    However, when I run this method, it returns 0, the initial value for the int mines, could anyone give me a hand as to what I am doing wrong?

    much better:
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.channels.FileChannel;
    import java.nio.charset.Charset;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class RegExpTest {
         public RegExpTest(){
              try {
                 // Create matcher on file
                 Pattern pattern = Pattern.compile("Optimal solution:\\s*(\\-)\\d");
                 Matcher matcher = pattern.matcher(fromFile("your_file_path_here.txt"));
                 // Find all matches
                 while (matcher.find()) {
                     // Get the matching string
                     String match = matcher.group();
                     System.out.println("Line : "+match);
                     int i = Integer.parseInt(match.substring(match.indexOf(':')+1).trim());
                     System.out.println("Number: "+i);
             } catch (IOException e) {
                  e.printStackTrace();
         //Converts the contents of a file into a CharSequence
        // suitable for use by the regex package.
        public CharSequence fromFile(String filename) throws IOException {
            FileInputStream fis = new FileInputStream(filename);
            FileChannel fc = fis.getChannel();
            // Create a read-only CharBuffer on the file
            ByteBuffer bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int)fc.size());
            CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);
            return cbuf;
        public static void main(String[] args) {
              new RegExpTest();
    }

  • ITunes changes links to music files to the wrong (and random) location

    Recently, I've noticed that iTunes (8.2) skips certain songs in my iTunes library. No ! shows up to indicate it cannot find the file. Rather, the file link is to a completely random location on my harddrive where no music files exist. I'll link to a photo a previous poster put on the web which has the same odd file links. http://farm4.static.flickr.com/3459/327398302018d78347a5o.jpg
    Two questions:
    1. How do I stop this?
    2. How can I fix this short of reimporting each file and deleting the improper one?
    Thanks in advance for any insights.
    Dan

    Remove the compilations indicator from the tracks and iTunes should relocated the files for you. Make a playlist to pick up all the tracks in the album, highlight all the songs and right click on the selection, choose Get Info and when you are asked if you want to edit multiple items say yes, In the box that opens change Compilation to "No" and press OK.

  • Save As dialog box opens random location

    I have been trying to save some attachments from my emails in entourage, but whenever it brings up the save dialog box, the default finder location is completely random. It is not based on my last known location, nor a default 'Desktop' or 'Documents' folder. It will change every time. I can save 3 emails in a row and they will all open in different locations....
    oddd....
    any thoughts?

    I too am having the same issue, in every program. Whenever I have a save dialog box open, it picks a completely random location to save it to, which becomes quite old when you have to save multiple files back-to-back in the same location. Anyone have any ideas?

  • My Final Cut Pro render files seem to end up in seemingly random locations.

    I find my Final Cut Pro render files seem to end up in seemingly random locations on the HDD. for example, they will appear in a sub-folder of an unrelated project. I would like my render files destination to be in a sub-folder for the project I am working on. How do you tell Final Cut where to put the render files? Can't figure it out.

    By default they are put inside your scratch folder, so if you change the scratch disk and forget to change it when you switch to a different project, your render files will be put inside the other project's scratch folder.
    You can change this by going to Final Cut Pro > System Settings. If you click the Set button below your current scratch disk (not the one next to it) you can assign a second location just for the video / audio renders if you desire (this must be on a different disk though).

  • PL/SQL function to read a string of characters into an array

    I was wondering if there is an easier way than using the substr function multiple times. Here is the example:
    Suppose you have a varchar2 variable that contains the word 'Apple'. The function should take it and produce an array. We would invoke it like this:
    <what data structure?> a := stringunpackerfunction(x);
    // x is the varchar2 containing 'Apple'.
    The resulting a would be such that a[0] is 'A', a[1] is 'p', a[2] is 'p', a[3] is 'l' and a[4] is 'e'.
    If there is no direct function to do this in a single invocation, is there a function to simply read a string of characters and return 'the next character'?
    Thanks,
    Regards,
    Srini

    There is a procedure out there called PS_PARSE which takes a string and converts to an array provided with an identified separator. Works for us pretty well.
    I just grabbed this off of google. I am presuming this should work fine. It has been sometime since we implemented ours that I forget if there were any additional modifications that we made. I think there was one regarding the size of the string that could be handled. I forget precisely. Anyways... take a peek at it. Its makes things easy in that your logic is pretty streamlined.
    Barry C
    http://www.myoracleportal.com
    create or replace PACKAGE PS_Parse
    IS
         || PL/SQL table structures to hold atomics retrieved by parse_string.
         || This includes the table type definition, a table (though you can
         || declare your own as well, and an empty table, which you can use
         || to clear out your table which contains atomics.
         TYPE atoms_tabtype IS TABLE OF VARCHAR2(60) INDEX BY BINARY_INTEGER;
         atoms_table atoms_tabtype;
         empty_atoms_table atoms_tabtype;
         || The standard list of delimiters. You can over-ride these with
         || your own list when you call the procedures and functions below.
         || This list is a pretty standard set of delimiters, though.
         std_delimiters VARCHAR2 (50) := ' !@#$%^&*()-_=+\|`~{{]};:''",<.>/?';
         /* Display contents of table using DBMS_OUTPUT */
         PROCEDURE display_atomics
              (table_in IN atoms_tabtype, num_rows_in IN NUMBER);
         || The parse_string procedure: I provide two, overloaded definitions.
         || The first version puts all atomics into a PL/SQL table and would
         || be used in a PL/SQL Version 2 environment. The second version places
         || all atomics into a string, separating each atomic by a vertical bar.
         || (My code does NOT do any special handling when it finds a "|" in
         || the string. You have to deal with that when you extract the atomics.
         ||
         || See the program definition for more details on other parameters.
         PROCEDURE parse_string
              (string_in IN VARCHAR2,
              atomics_list_out OUT atoms_tabtype,
              num_atomics_out IN OUT NUMBER,
              delimiters_in IN VARCHAR2 := std_delimiters);
         PROCEDURE parse_string
              (string_in IN VARCHAR2,
              atomics_list_out IN OUT VARCHAR2,
              num_atomics_out IN OUT NUMBER,
              delimiters_in IN VARCHAR2 := std_delimiters);
         /* Count the number of atomics in a string */
         FUNCTION number_of_atomics
              (string_in IN VARCHAR2,
              count_type_in IN VARCHAR2 := 'ALL',
              delimiters_in IN VARCHAR2 := std_delimiters)
         RETURN INTEGER;
         /* Return the Nth atomic in the string */
         FUNCTION nth_atomic
              (string_in IN VARCHAR2,
              nth_in IN NUMBER,
              count_type_in IN VARCHAR2 := 'ALL',
              delimiters_in IN VARCHAR2 := std_delimiters)
         RETURN VARCHAR2;
    END PS_Parse;
    create or replace PACKAGE BODY PS_Parse
    IS
    /* Package variables used repeatedly throughout the body. */
    len_string     NUMBER;
    start_loc     NUMBER;
    next_loc     NUMBER;     
    || Since the PUT_LINE procedure regards a string of one or more
    || spaces as NULL, it will not display a space, which is in
    || PS_Parse a valid atomic. So I save a_blank in the PL/SQL
    || table instead of the space itself.
    a_blank CONSTANT VARCHAR2(3) := '" "';
    /*--------------------- Private Modules ---------------------------
    || The following functions are available only to other modules in
    || package. No user of PS_Parse can see or use these functions.
    FUNCTION a_delimiter
    (character_in IN VARCHAR2,
    delimiters_in IN VARCHAR2 := std_delimiters)
    RETURN BOOLEAN
    || Returns TRUE if the character passsed into the function is found
    || in the list of delimiters.
    IS
    BEGIN
    RETURN INSTR (delimiters_in, character_in) > 0;
    END;
    FUNCTION string_length (string_in IN VARCHAR2)
    RETURN INTEGER
    IS
    BEGIN
    RETURN LENGTH (LTRIM (RTRIM (string_in)));
    END;
    FUNCTION next_atom_loc
    (string_in IN VARCHAR2,
    start_loc_in IN NUMBER,
    scan_increment_in IN NUMBER := +1)      
    || The next_atom_loc function returns the location
    || in the string of the starting point of the next atomic (from the
    || start location). The function scans forward if scan_increment_in is
    || +1, otherwise it scans backwards through the string. Here is the
    || logic to determine when the next atomic starts:
    ||
    ||          1. If current atomic is a delimiter (if, that is, the character
    ||               at the start_loc_in of the string is a delimiter), then the
    ||               the next character starts the next atomic since all
    ||               delimiters are a single character in length.
    ||
    ||          2. If current atomic is a word (if, that is, the character
    ||               at the start_loc_in of the string is a delimiter), then the
    ||               next atomic starts at the next delimiter. Any letters or
    ||               numbers in between are part of the current atomic.
    ||
    || So I loop through the string a character at a time and apply these
    || tests. I also have to check for end of string. If I scan forward
    || the end of string comes when the SUBSTR which pulls out the next
    || character returns NULL. If I scan backward, then the end of the
    || string comes when the location is less than 0.
    RETURN NUMBER
    IS
    /* Boolean variable which uses private function to determine
    || if the current character is a delimiter or not.
    was_a_delimiter BOOLEAN :=
    PS_Parse.a_delimiter (SUBSTR (string_in, start_loc_in, 1));     
    /* If not a delimiter, then it was a word. */
    was_a_word BOOLEAN := NOT was_a_delimiter;
    /* The next character scanned in the string */
              next_char VARCHAR2(1);
    || The value returned by the function. This location is the start
    || of the next atomic found. Initialize it to next character,
    || forward or backward depending on increment.
    return_value NUMBER := start_loc_in + scan_increment_in;
    BEGIN
    LOOP
    -- Extract the next character.
    next_char := SUBSTR (string_in, return_value, 1);
    -- Exit the loop if:
    EXIT WHEN
    /* On a delimiter, since that is always an atomic */
    a_delimiter (next_char)
    OR
    /* Was a delimiter, but am now in a word. */
    (was_a_delimiter AND NOT a_delimiter (next_char))
    OR
    /* Reached end of string scanning forward. */
    next_char IS NULL
    OR
    /* Reached beginning of string scanning backward. */
    return_value < 0;
    /* Shift return_value to move the next character. */
    return_value := return_value + scan_increment_in;
    END LOOP;
    -- If the return_value is negative, return 0, else the return_value
    RETURN GREATEST (return_value, 0);
    END;
    PROCEDURE increment_counter
    (counter_inout IN OUT NUMBER,
    count_type_in IN VARCHAR2,
    atomic_in IN CHAR)
    || The increment_counter procedure is used by nth_atomic and
    || number_of_atomics to add to the count of of atomics. Since you
    || can request a count by ALL atomics, just the WORD atomics or
    || just the DELIMITER atomics. I use the a_delimiter function to
    || decide whether I should add to the counter. This is not a terribly
    || complex procedure. I bury this logic into a separate module,
    however,
    || to make it easier to read and debug the main body of the programs.
    IS
    BEGIN
    IF count_type_in = 'ALL' OR
    (count_type_in = 'WORD' AND NOT a_delimiter (atomic_in)) OR
    (count_type_in = 'DELIMITER' AND a_delimiter (atomic_in))
    THEN
    counter_inout := counter_inout + 1;
    END IF;
    END increment_counter;
    /* ------------------------- Public Modules -----------------------*/
    PROCEDURE display_atomics
    (table_in IN atoms_tabtype, num_rows_in IN NUMBER)
    || Program to dump out contents of table. Notice I must also pass in
    || the number of rows in the table so that I know when to stop the
    || loop. Otherwise I will raise a NO_DATA_FOUND exception. For a more
    || elaborate display_table module, see Chapter 7 on PL/SQL tables.
    IS
    BEGIN
    FOR table_row IN 1 .. num_rows_in
    LOOP
    DBMS_OUTPUT.PUT_LINE (NVL (table_in (table_row), 'NULL'));
    END LOOP;
    END;
    PROCEDURE parse_string
    (string_in IN VARCHAR2,
    atomics_list_out OUT atoms_tabtype,
    num_atomics_out IN OUT NUMBER,
    delimiters_in IN VARCHAR2 := std_delimiters)
    || Version of parse_string which stores the list of atomics
    || in a PL/SQL table.
    ||
    || Parameters:
    ||          string_in - the string to be parsed.
    ||          atomics_list_out - the table of atomics.
    ||          num_atomics_out - the number of atomics found.
    ||          delimiters_in - the set of delimiters used in parse.
    IS
    BEGIN
    /* Initialize variables. */
    num_atomics_out := 0;
    len_string := string_length (string_in);
    IF len_string IS NOT NULL
    THEN
    || Only scan the string if made of something more than blanks.
    || Start at first non-blank character. Remember: INSTR returns 0
    || if a space is not found. Stop scanning if at end of string.
    start_loc := LEAST (1, INSTR (string_in, ' ') + 1);
    WHILE start_loc <= len_string
    LOOP
    || Find the starting point of the NEXT atomic. Go ahead and
    || increment counter for the number of atomics. Then have to
    || actually pull out the atomic. Two cases to consider:
    ||          1. Last atomic goes to end of string.
    ||          2. The atomic is a single blank. Use special constant.
    ||          3. Anything else.
    next_loc := next_atom_loc (string_in, start_loc);
    num_atomics_out := num_atomics_out + 1;
    IF next_loc > len_string
    THEN
    -- Atomic is all characters right to the end of the string.
    atomics_list_out (num_atomics_out) :=
    SUBSTR (string_in, start_loc);
    ELSE
    || Internal atomic. If RTRIMs to NULL, have a blank
    || Use special-case string to stuff a " " in the table.
    atomics_list_out (num_atomics_out) :=
    NVL (RTRIM (SUBSTR (string_in,
    start_loc, next_loc-start_loc)),
                                       a_blank);
    END IF;
    -- Move starting point of scan for next atomic.
    start_loc := next_loc;
    END LOOP;
    END IF;
    END parse_string;
    PROCEDURE parse_string
    (string_in IN VARCHAR2,
    atomics_list_out IN OUT VARCHAR2,
    num_atomics_out IN OUT NUMBER,
    delimiters_in IN VARCHAR2 := std_delimiters)
    || The version of parse_string which writes the atomics out to a packed
    || list in the format "|A|,|C|". I do not repeat any of the comments
    || from the first iteration of parse_string.
    IS
    BEGIN
    /* Initialize variables */
    num_atomics_out := 0;
    atomics_list_out := NULL;
    len_string := string_length (string_in);
    IF len_string IS NOT NULL
    THEN
    start_loc := LEAST (1, INSTR (string_in, ' ') + 1);
    WHILE start_loc <= len_string
    LOOP
    next_loc := next_atom_loc (string_in, start_loc);
    num_atomics_out := num_atomics_out + 1;
    IF next_loc > len_string
    THEN
    atomics_list_out := atomics_list_out || '|' ||      
    SUBSTR (string_in, start_loc);
    ELSE
    atomics_list_out :=
    atomics_list_out || '|' ||      
    NVL (RTRIM (SUBSTR (string_in,
    start_loc, next_loc-start_loc)),
                                       a_blank);
    END IF;
    start_loc := next_loc;
    END LOOP;
    /* Apply terminating delimiter to the string. */
    atomics_list_out := atomics_list_out || '|' ;
    END IF;
    END parse_string;
    FUNCTION number_of_atomics
    (string_in IN VARCHAR2,
    count_type_in IN VARCHAR2 := 'ALL',
    delimiters_in IN VARCHAR2 := std_delimiters)
    RETURN INTEGER
    || Counts the number of atomics in the string_in. You can specify the
    || type of count you want: ALL for all atomics, WORD to count only the
    || words and DELIMITER to count only the delimiters. You can optionally
    || pass your own set of delimiters into the function.
    IS
    return_value INTEGER := 0;
    BEGIN
    /* Initialize variables. */
    len_string := string_length (string_in);
    IF len_string IS NOT NULL
    THEN
    || This loop is much simpler than parse_string. Call the
    || next_atom_loc to move to the next atomic and increment the
    || counter if appropriate. Everything complicated is shifted into
    || sub-programs so that you can read the program "top-down",
    || understand it layer by layer.
    start_loc := LEAST (1, INSTR (string_in, ' ') + 1);
    WHILE start_loc <= len_string
    LOOP
    increment_counter (return_value, UPPER (count_type_in),
    SUBSTR (string_in, start_loc, 1));
    start_loc := next_atom_loc (string_in, start_loc);
    END LOOP;
    END IF;
    RETURN return_value;
    END number_of_atomics;
    FUNCTION nth_atomic
    (string_in IN VARCHAR2,
    nth_in IN NUMBER,
    count_type_in IN VARCHAR2 := 'ALL',
    delimiters_in IN VARCHAR2 := std_delimiters)
    RETURN VARCHAR2
    || Find and return the nth atomic in a string. If nth_in is greater
    || the number of atomics, then return NULL. If nth_in is negative the
    || function counts from the back of the string. You can again request
    || a retrieval by ALL atomics, just the WORDs or just the DELIMITER.
    || So you can ask for the third atomic, or the second word from the end
    || of the string. You can pass your own list of delimiters as well.
    IS
    /* Local copy of string. Supports up to 1000 characters. */
    local_string VARCHAR2 (1000) :=
    LTRIM (RTRIM (SUBSTR (string_in, 1, 1000)));
    /* Running count of atomics so far counted. */
    atomic_count NUMBER := 1;
    /* Boolean variable which controls the looping logic. */
    still_scanning BOOLEAN :=
    local_string IS NOT NULL AND nth_in != 0;
    /* The amount by which I increment the counter. */
    scan_increment INTEGER;
    /* Return value of function, maximum length of 100 characters. */
    return_value VARCHAR2 (100):= NULL;
    BEGIN
    IF nth_in = 0
    THEN
    /* Not much to do here. Find 0th atomic? */
    RETURN NULL;
    ELSE
    /* Initialize the loop variables. */
    len_string := string_length (local_string);
    IF nth_in > 0
    THEN
    /* Start at first non-blank character and scan forward. */
    next_loc := 1;
    scan_increment := 1;
    ELSE
    /* Start at last non-blank character and scan backward. */
    next_loc := len_string;
    scan_increment := -1;
    END IF;
    /* Loop through the string until the Boolean is FALSE. */
    WHILE still_scanning
    LOOP
    /* Move start of scan in string to loc of last atomic. */
    start_loc := next_loc;
    /* Find the starting point of the next atomic. */
    next_loc      :=
    next_atom_loc (local_string, start_loc, scan_increment);
    /* Increment the count of atomics. */
    increment_counter
    (atomic_count,
    UPPER (count_type_in),
    SUBSTR (local_string, start_loc, 1));
    || Keep scanning if my count hasn't exceeded the request
    || and I am neither at the beginning nor end of the string.
    still_scanning :=
    atomic_count <= ABS (nth_in) AND
    next_loc <= len_string AND
    next_loc >= 1;
    END LOOP;
    || Done with the loop. If my count has not exceeded the requested
    || amount, then there weren't enough atomics in the string to
    || satisfy the request.
    IF atomic_count <= ABS (nth_in)
    THEN
    RETURN NULL;
    ELSE
    || I need to extract the atomic from the string. If scanning
    || forward, then I start at start_loc and SUBSTR forward.
    || If I am scanning backwards, I start at next_loc+1 (next_loc
    || is the starting point of the NEXT atomic and I want the
    || current one) and SUBSTR forward (when scanning in
    || reverse, next_loc comes before start_loc in the string.
    IF scan_increment = +1
    THEN
    RETURN
    SUBSTR (local_string, start_loc, next_loc - start_loc);
    ELSE
    RETURN
    SUBSTR (local_string, next_loc+1, start_loc - next_loc);
    END IF;
    END IF;
    END IF;
    END nth_atomic;
    END PS_Parse;
    /

  • Document opens to random location

    My friend and I are both using CS4 on Macs, we each ran Leopard and upgraded to Snow Leopard, but he has always had a problem with InDesign opening documents to random locations, rather than the last saved location. I've never had a problem with that... InDesign always opens to the place where I last saved. He's had this problem in both Leopard and Snow Leopard. Any ideas?
    Thanks!
    Mark

    My part of the project involves editing 3 separate files that will later be joined in a single multi-paned document. These 3 are being edited against a preexisting 4th, which has the content of an earlier version. The 3 primary files are edited constantly. The 4th is only edited when an error is noticed (i.e., I sometimes stumble upon errors in the earlier version, in the process of referencing it to create the new version; when I do, I fix them).
    I am almost positive that I leave the cursor at the last known position of editing when each document is saved and ID is closed for the day. This is something we can easily verify with two people looking. For additional testing, I will try to start making a minor change/change-back at the end of my work for the day, so that the cursor can be clearly seen at the last save point for each file. I will document this process, making a note of the exact cursor position at the final save and close point. Then I will document exactly where the cursor appears for each file when opening for the next day's work.
    Can you think of anything else I should track should this turn out to be a bug? (I usually have at least 8 apps and a couple of backup processes running all the time.)
    Thanks!

  • Reading Each String From a text File

    Hello everyone...,
    I've a doubt in File...cos am not aware of File.....Could anyone
    plz tell me how do i read each String from a text file and store those Strings in each File...For example if a file contains "Java Tchnology forums, File handling in Java"...
    The output should be like this... Each file should contains each String....i.e..., Java-File1,Technology-File2...and so on....Plz anyone help me

    The Java� Tutorials > Essential Classes: Basic I/O

  • Read AVI string in matlab

    I have saved string data in an AVI file with ''IMAQ AVI Write Frame". I have checked the saved data in Labview and when I read this AVI file with "AVI read data" it is possible to read the sting.
    However, I want to read the data into Matlab and cannot find a way to extract the string data from the AVI file. AVI data can be read with 'VideoReader', but this doesn't read the string data. Does anybody knows a method to read the string data into matlab?
    If anyone can help me it would be really great!

    Dear researchIC,
    I do not know what are the possibilities in Matlab to deal with AVI file.
    However, what I can tell you is that the data which is included in the file with the "IMAQ AVI Write Frame" is not encrypted or anything. It is simply included in a standard data stream of the AVI file. It is then potentialy possible to read back the data in a third-party application.
    The best advice I can give you is then to inform you about the AVI file format and see how you can retrieve the information contained in a stream.
    Cédric | NI Belgium

  • Reading a String with dynamic format.

    Hello,
    I'm learning Java and I'm relatively new to the scene. I decided to make a small free utility with the hope that it will help somebody. The utility is a Game Server (Call of Duty 4) connector that will help Administrators to connect to the server and execute commands without the need of running the game.
    I have made a progress so far by searching these (very useful) forums but I came across a point that I can't by pass.
    The only way to learn "Who Is" from the server is the rcon command "status". Using this command the server returns you the current map and the players playing with all their information. This is the part of the code that I need help at:
    public static void StatusReader(String StatusInput) throws IOException {
                     ArrayList line = new ArrayList();
                        BufferedReader br = new BufferedReader(new StringReader(StatusInput));
                       String s = null;
                       int l=0;
                  dokimi = StatusInput.split("\n");
             //    for(int j=0;j<9;j++){
              //        int i=0;
              //        dokimi2 = new String[0][0];
              //        dokimi2[0][0] = dokimi[0];
              //        System.out.println(dokimi2[0][0]);
                  System.arraycopy(dokimi, 0, dokimi2, 0, 1);
                for(int i=0;i<(dokimi.length/9);i++){
                        for(int j=0;j<9;j++){    
                       dokimi2 = new String[i][j];
                       System.arraycopy(dokimi, 0, dokimi2[i][j], 0, 1);
                       System.out.println(dokimi2[i][j]);
             //     while ((s = br.readLine()) != null)
                  //     line.add(s);
                   //  StatusOutput = new String[line.size()][];
                  //     for (int i = 0; i < StatusOutput.length; i++) {
                  //               s = (String) line.get(i);
                       //          StringTokenizer st = new StringTokenizer(s, "");
                  //               String[] arr = new String[st.countTokens()];
    //                       for (int j = 0; j < arr.length; j++)
      //                                arr[j] = st.nextToken();
            //               StatusOutput[i] = arr;
               //          for (int i = 0; i < StatusOutput.length; i++) {
          //                    for (int j = 0; j < StatusOutput.length; j++)
    //                         System.out.print(StatusOutput[i][j] + " ");
         //                    System.out.println();
    }I've been messing a lot with the code. +_What I want to do is to read this string that the server is sending,split it, and then place it in a 2D Array that I will attach on a table._+ So far I've made the StringTokenizer method to be able to , kind of, sort that String and put it in an array. However I usually get outofbounds errors because not always the lines have the same length. This is an example of the format that the server sends after executing the "status" command:map: mp_crossfire
    num score ping guid name lastmsg address qport rate
    2 1 84 b5e9d93e88670c6f811a033a7f925117 Davis^7 0 84.185.183.210:-1482 21249 25000
    4 15 100 e0d7c91fa7ba9549444ccab3a0e3de62 =HPX= Anogianos^7 0 91.140.25.93:28960 -10752 25000
    5 5 68 5d68298d9e16d7491d5700e6e236214f AsChIkUtAbU^7 50 84.60.215.190:17502 26401 25000
    6 115 44 cc503f50d990e27eeb990826c2cf1193 Donnergroll^7 50 91.64.153.240:28960 10086 25000
    7 141 79 cbd095d37abdc728671e2923296aa9cf souL^7 50 87.78.179.242:-10509 8432 25000
    8 116 83 4d0d1a067179516e209ef89cb0a79755 suodeth^7 0 84.250.214.156:27185 -29970 25000
    9 11 117 fc3c6777b3d9bf99df1e55b321b75e9e shpalman^7 50 62.101.126.209:-17420 -25455 25000
    10 5 82 fb2f20a9f46a212b896baf9ab4ea3eb0 =HPX=Gringo^7 50 213.5.170.94:-619 20175 25000
    11 95 68 d3d542b17ab56d9fbf107da39f245269 aga^7 50 78.2.42.253:28960 22173 25000
    12 10 100 8e6d08aec08591fb319081d0b40dedd2 madmax^7 0 79.166.47.145:2960 -7933 25000
    13 110 77 4fc4d0e24faa634dbce5c4bb4131bc4a Thunderstorm^7 50 87.78.113.218:28960 4512 25000
    14 55 67 f789227fcb95853b857115e68741df8d Robbino^7 0 89.217.12.113:28960 -192 25000
    15 118 85 b7be8ce58324d0f25c45f5cb372b30a1 Paranoid^7 50 78.1.26.32:28960 27294 25000
    16 11 90 38b59f3bbd3aa0ce3c95fccb26858931 $Hockz^7 50 87.181.101.96:-2984 24219 25000
    19 16 45 720f2abf81189890851d3e41fcbe4e21 ERASER^7 50 83.236.63.150:-32135 24704 25000
    20 145 37 a78f43bc3d3705743a190de45d37fc6a KintaKunte^7 50 88.68.237.239:28960 23539 25000
    21 60 49 a96d6a55049d11c5d7cd1c35c4d497c3 #sD|-HaZarD-^7 50 87.78.179.242:-10509 8432 25000
    8 116 83 4d0d1a067179516e209ef89cb0a79755 suodeth^7 0 84.250.214.156:27185 -29970 25000
    9 11 117 fc3c6777b3d9bf99df1e55b321b75e9e shpalman^7 50 62.101.126.209:-17420 -25455 25000
    10 5 82 fb2f20a9f46a212b896baf9ab4ea3eb0 =HPX=Gringo^7 50 213.5.170.94:-619 20175 25000
    11 95 68 d3d542b17ab56d9fbf107da39f245269 aga^7 50 78.2.42.253:28960 22173 25000
    12 10 100 8e6d08aec08591fb319081d0b40dedd2 madmax^7 0 79.166.47.145:2 0 91.3.110.248:-1185 6274 25000
    23 116 109 bfffdf9ff93425d284796532ef214bd0 ze_meedles^7 50 85.243.221.116:28960 24936 25000
    95853b857115e68741df8d Robbino^7 0 89.217.12.113:28960 -192 25000
    15 118 85 b7be8ce58324d0f25c45f5cb372b30a1 Paranoid^7 50 78.1.26.32:28960 27294 25000
    16 11 90 38b59f3bbd3aa0ce3c95fccb26858931 $Hockz^7 50 87.181.101.96:-2984 24219 25000
    19 16 45 720f2abf81189890851d3e41fcbe4e21 ERASER^7 50 83.236.63.150:-32135 24704 25000
    20 145 37 a78f43bc3d3705743a190de45d37fc6a KintaKunte^7 50 88.68.237.239:28960 23539 25000
    21 60 49 a96d6a55049d11c5d7cd1c35c4d497c3 #sD|-HaZarD-^7 50 87.78.179.242:-10509 8432 25000
    8 116 83 4d0d1a067179516e209ef89cb0a79755 suodeth^7 0 84.250.214.156:27185 -29970 25000
    9 11 117 fc3c6777b3d9bf99df1e55b321b75e9e shpalman^7 50 62.101.126.209:-17420 -25455 25000
    10 5 82 fb2f20a9f46a212b896baf9ab4ea3eb0 =HPX=Gringo^7 50 213.5.170.94:-619 20175 25000
    11 95 68 d3d542b17ab56d9fbf107da39f245269 aga^7 50 78.2.42.253:28960 22173 25000
    12 10 100 8e6d08aec08591fb319081d0b40dedd2 madmax^7 0 79.166.47.145:2As you can see the problem is that the server sends some information twice *but* it splits them with a blank line. In addition some nicknames contain spaces something that makes me wonder how I can set the nicknames to belong to the same position of the array. Something that i know is that all nicknames end with "^7" which is the in-game colour definition. Any help would be much appreciated. Thanks in advance.
    Edited by: m33ts4k0z on Dec 21, 2007 11:36 AM
    Edited by: m33ts4k0z on Dec 21, 2007 11:43 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    m33ts4k0z wrote:
    Hello DeltaGeek and thanks for your answer.
    I have 2 questions for you since you mentioned what the real problem is. The first question is how can I join 2 cells that will contain the 2 parts of the nickname in case of a space? Can I just check if the cell number x,y contains "^7" and then just copy that cell the x,y-1? Ive tried that but then I also have to move the rest of the columns to y-1 as well. Any idea how to do that?
    I was assuming you'd be processing the split string anyways, and not just tossing it into your 2-d structure. If you want to use .split(), yes. you would need to merge those cells into the original name. System.arrayCopy() would likely be useful for doing most of the heavy lifting.
    Another option you have is to tokenize the string using Scanner. That would let you pull each column out of the string individually. You'll need to populate the array manually (instead of just using what .split() gives you), but allows you to change the token delimiter between pulls.
    As for the junk lines, I can just check if they don't much the tokens number and then just not add them to the array I suppose, am I right or....?That's certainly one option. I don't know what's being given back to you, it may be important.

  • Reading a string.

    Hi experts.
    how can i read a string at a specified character.
    For ex: i have  astring like this.
    str = 'YUGFHKGHKHDKHHHGJK8HJBFXJKKFKJFJKFHJH'.
    so i have to read n.of charecters from starting of the string to charecter 8.
    Not with search option.
    Regards

    Hi,
    Thank you all.
    I know all these but in my program it is not workig..Don't know why...
    either split or search.Pls see the below sample code.
    DATA  : i_files like spflist occurs 0 with header line,
    DATA: w_files LIKE LINE OF  i_files.
    data: str1(200) type c,
          str2(200) type c.
    LOOP AT i_files INTO w_files.
        str = w_files-line.
        lin1 = STRLEN( str ).
        lin1 = lin1 - 1.(this is because there is one more '#' at the end of string)
        str = str+0(lin1).
        lin2 = STRLEN( str ).
        search str for '#'.
        split str at '#' into str1 atr2.    
        w_files-line = str.
        MODIFY i_files FROM w_files.
        CLEAR lin1.
      ENDLOOP.
    Suppose here str contains:
    str = '00000003379#212RegVNegNoticeHLA.aspx.xml'.
    So i am getting sy-subrc = 4 after search.
    and after split there are no values in str2..and str1 contains full string..
    Can any body tell me what may be the problem..?
    Regards

  • Reading a String Literally - Finding the "\" Character with a Regex

    How do I search for "\" characters in a string? Such as..
    String text = "Temp\temp.txt";
    The problem is that Java will read "\t" as a tab, so that
    System.out.println(text);
    Will return
    Temp emp.txt
    Also, searching for the regex "\\\\" will return a null result, presumably because Java interprets the "\t" as a tab character, not as a literal "\" followed by a literal "t".
    How do I get Java to read the string without interpreting it?
    Thanks in advance

    Try also this:
    public static void main(String[] args) {
              String test1 = "String with a\\t which is not a tab but a t preceeded with a \\ character";
              String test2 = "String with a \t which is a tab";
              System.out.println("This are the Strings as user sees / enters them:");
              System.out.println(test1);
              System.out.println(test2);
              System.out.println("");
              System.out.println("***********************************************************");
              System.out.println("");
              System.out
                        .println("Splitting first string using a \\\\\\\\ regex which will be interpreted by the regex engine as \\\\ which will represent a \'\\\' character:");
              System.out.println("");
              for (String s : test1.split("\\\\")) {
                   System.out.println(s);
              System.out.println("");
              System.out.println("***********************************************************");
              System.out.println("");
              System.out.println("Splitting the second string just the same way:");
              System.out.println("");
              for (String s : test2.split("\\\\")) {
                   System.out.println(s);
         }and read the console output.
    It should be:
    This are the Strings as user sees / enters them:
    String with a\t which is not a tab but a t preceeded with a \ character
    String with a       which is a tab
    Splitting first string using a \\\\ regex which will be interpreted by the regex engine as \\ which will represent a '\' character:
    String with a
    t which is not a tab but a t preceeded with a
    character
    Splitting the second string just the same way:
    String with a       which is a tab

  • How to read from a certain location is a file?

    hi! i am new to programing and i have a problems abt reading from a file. i have write the following to a file using FmtFile :
    10 (a numbers)
    name,phone,product (some strings)
    9 (a numbers)
    when i user ScanFile to read the second number(9 in the above example), i got a wrong value. the command i use is:
    ScanFile (filehandle, "%d", &number1);
    ScanFile (filehandle, "%s[t44]%s[t44]%s",name, phone product);
    ScanFile (filehandle, "%d", &number2);
    number1 and number 2 are integers and name, phone and product are char arrays.
    can anyone tell me where have i gone wrong? or maybe someone can tell me how can i read the 2nd number without reading the 1st number
    and the strings.

    Let's look at your file: if I correctly interpret your question, one row in it should like like this:
    10,name,phone,product,9
    In this case you could use the following formatting string to read all data from the string:
    "%d[x]%s[xt44]%s[xt44]%s[xt44]%d"
    [x] means to discard terminator, in order to read from strings, for example, "name" and not "name,". It's important in this case to put ALL field separators.
    Maybe your problem is that in the file you don't have separators between strings and numbers: in this case the last "%s" should read the '9' inside the last string and the subsequent "%d" matches with incorrect area in the file (end-of-line or next row).
    Hope this help
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • How can i read a string with nextToken() of StreamTokenizer

    I need for my class paper to read a string from a file and i used the StreamTokenizer's method nextToken but i can not read a string with it. my code is:
    StreamTokenizer st = new StreamTokenizer(the code that gets the input from the file)
    String line;
    while ((line !=br.readLine()) != null) {
    String surname = (st.nextToken()).trim();
    but it gets me some error of:
    int can not be dereferenced
    what should I do to get the string i need?

    Look at the API for java.io.StreamTokenizer. In particular, look at the return type for nextToken().
    Good luck.

  • Java.io.Reader to String conversion

    I am working on a SOAP project with Jaxm and I retreive the result as a Reader, but I need to convert it into a String.
    I did the following code but it is incredibely slow with a big reply (280kb) as I retrieve each character one after each other.
    Does a faster solution exist ?
    // Soap call
    SOAPMessage reply = m_conn.call(message, endpoint);
    java.util.Iterator it = reply.getAttachments();
    // First attachment returned by the server hold my result
    AttachmentPart resultAttachment = (AttachmentPart) it.next();
    StreamSource resultStreamSource = (StreamSource) resultAttachment.getContent();
    // Converts java.io.Reader to String
    java.io.Reader resultReader = resultStreamSource.getReader();
    String result = "";
    int charValue = 0;
    while ((charValue = resultReader.read()) != -1) {
       result = result + (char) charValue;

    use a BufferedReader and create a large char[] (64k or something)
    then use
    char[] cbuf = new char[65536];
    StringBuffer stringbuf = new StringBuffer();
    int read_this_time = 0;
    while (read_this_time != -1) {
    read_this_time = BufferedReader.read(cbuf,0,65536);
    stringbuf.append(cbuf,0,read_this_time);
    }//end while
    StringBuffer is faster than String concatenation because when java concatenates strings it creates a new object every time. StringBuffer just stores and appends the string without creating new objects.

Maybe you are looking for

  • How to see, if some user has done multiple login at the same time

    Hi, i'm looking for a tcode to see, if some user has done multiple login in a date-range. Regards, Dieter

  • Updating WBS element in a sales order

    There is application in Project System (PS) module where I am creating the Project using bapi BAPI_PROJECT_MANTAIN and then uploading the budget for the same using bapi KBPP_EXTERN_UPDATE_CO. After this when I am trying to update the sales order to u

  • Installing Windows XP after Arch Linux already been installed [SOLVED]

    Here is my dilema: I have a Fujitsu Lifebook T4010 Laptop with a Wacom Tablet built into the screen. About a month ago I installed Arch Linux on it. It took me a while to get everything working (tablet screen/function buttons/on rotate flip reso) but

  • Both Individual & Collective requirement for Same material

    Hi, Is it possible to have a component as, dependent requirement in one B.o.M as individual requirement & in another  B.o.M as collective requirement. Suppose we have 2 Production version Bill of material 1 FG (Make to Order) SFG2 (Individual planned

  • Is there a tag called left_col in HTML5 ?

    Just started watching a Lynda.com video tutorial called: "Creating a First Website with DW-CC-2014". Not sure if I'm missing something, but, near the beginning of the course Paul Trani features a video of the code view where an HTML5 tag called left_