Adding a line to an extrenal file

hi!
I am writing a program but am having a small problem with a bit that I just can't seem to work out!
I have a method that gets details from the user to add to an external file. However, When the data is added it doesnt just add it and shift the already there data down but instead it stores it under the first entry shifts the rest down and deletes the rest.
this is the code snippit:
               System.out.print("last name: ");
               last_name = dataInput.next();
               System.out.print("first name: ");
               first_name = dataInput.next();
               System.out.print("telephone: ");
               tel_num = dataInput.next();
               System.out.print("email: ");
                                                                  email_addr = dataInput.next();
               System.out.printf("");
               int z = 0;
               for (int i=0; i < number_of_records; i++)
                    if ((last_name.compareTo(lastName)) < i && (last_name.compareTo(lastName[i]) > i))
                         z = i;
               for (int i = number_of_records; i > z; i--)
                    lastName[i] = lastName[i-0];
                    firstName[i] = firstName[i-0];
                    telNumber[i] = telNumber[i-0];
                    emailAddress[i] = emailAddress[i-0];
               lastName[z+1] = last_name;
               firstName[z+1] = first_name;
               telNumber[z+1] = tel_num;
               emailAddress[z+1] = email_addr;
Anyone got any ideas what I am doing wrong?

I have a method that gets details from the user to
add to an external file. However, When the data is
added it doesnt just add it and shift the already
there data down but instead it stores it under the
first entry shifts the rest down and deletes the
rest. Uh, where in your snippet are you writing to a file?
And you know that you can't add to the beginning of a file, do you? You can only append to its end. So for some reason, what you describe sounds a little fishy. I can't guess what you'Re doing there.
Anyway, why don't you simply append to the file?

Similar Messages

  • [svn:osmf:] 14411: Adding command line build config files for the syndication library.

    Revision: 14411
    Revision: 14411
    Author:   [email protected]
    Date:     2010-02-24 17:45:22 -0800 (Wed, 24 Feb 2010)
    Log Message:
    Adding command line build config files for the syndication library.
    Added Paths:
        osmf/trunk/libs/Syndication/syndication-build-config.flex
        osmf/trunk/libs/Syndication/syndication-build-config.flexcov
        osmf/trunk/libs/Syndication/syndication-build-config.xml

    Revision: 14411
    Revision: 14411
    Author:   [email protected]
    Date:     2010-02-24 17:45:22 -0800 (Wed, 24 Feb 2010)
    Log Message:
    Adding command line build config files for the syndication library.
    Added Paths:
        osmf/trunk/libs/Syndication/syndication-build-config.flex
        osmf/trunk/libs/Syndication/syndication-build-config.flexcov
        osmf/trunk/libs/Syndication/syndication-build-config.xml

  • Passing lines in a text file to an array

    Hi,
    I did a search on this, looked through the tutorials. I want to read in a line from a text file and pass it to an array. here's my code:
    package pack1;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.util.Scanner;
    public class CDSort {
          * write a program that will read a bunch of cd's from a textfile,
          * count how many there are, and figure out how many cd boxes I will need based
          * on a fixed amount that will fit in each box. The cd's should be sorted alphabetically,
          * and each should be placed in a numbered box, and have a numbered position within that box
         public static void main(String[] args)throws Exception {
              java.io.File cdlist = new java.io.File("files/cd-list.txt");
              FileReader infile = new FileReader(cdlist);
              FileWriter outfile = new FileWriter("files/newlist.txt");
              if (cdlist.exists()){
                   System.out.println( cdlist.getName() + " exists at " + cdlist.getAbsolutePath());
                   System.out.println("this file was last modified on: " + new java.util.Date(cdlist.lastModified()));
                   int c;
                   while ((c = infile.read()) != -1) {
                        System.out.println(c);
                        String [] textArray = new String[99];
                             for(int i =0; i<textArray.length; i++){
                                  // trying to pass text to array here: I tried this, but got an error:
                                  //textArray[i] = infile.read(c);
                                  // i added this statement so I could see what the value of the array was on the console
                                  System.out.println(textArray[i] + i);
                        outfile.write(c);
                   infile.close();
                   outfile.close();
              } else
                   System.exit(0);
    }This is probably a pretty basic question, but my hunting arround hasn't really yielded anything.

    okay, here's what I did, this seems to work.
    package pack1;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.PrintStream;
    public class CDSort {
          * write a program that will read a bunch of cd's from a textfile,
          * count how many there are, and figure out how many cd boxes I will need based
          * on a fixed amount that will fit in each box. The cd's should be sorted alphabetically,
          * and each should be placed in a numbered box, and have a numbered position within that box
         public static void main(String[] args)throws Exception {
              java.io.File cdlist = new java.io.File("cd-list.txt");
              FileReader infile = new FileReader(cdlist);
              //FileWriter outfile = new FileWriter("newlist.txt");
              BufferedReader br = new BufferedReader(infile);
              BufferedWriter out = new BufferedWriter(new FileWriter("newlist.txt"));
              if (cdlist.exists()){
                   System.out.println( cdlist.getName() + " exists at " + cdlist.getAbsolutePath());
                   System.out.println("this file was last modified on: " + new java.util.Date(cdlist.lastModified()));
                   // while loop was here, I removed it.
                   String [] textArray = new String[99];
                   String line;
                   int lineNum = 0;
                   while ((line = br.readLine()) != null){
                        textArray[lineNum++] = line;
                        System.out.println(line);
                   int numOfCds = 1;
                   int boxNum = 1;
                   int boxPos = 1;
                   int cdsPerBox = 20;
                   out.write("Contents of Box " + boxNum);
                   out.newLine();
                   out.newLine();
                   for(int i = 0; i<textArray.length; i++){
                        out.write(textArray[i] + " box position: " + boxPos + "\n");
                        out.newLine();
                        boxPos++;
                        numOfCds++;
                        if (boxPos >= cdsPerBox){
                             boxNum++;
                             out.newLine();
                             out.newLine();
                             out.write("Contents of Box " + boxNum);
                             out.newLine();
                             out.newLine();
                             boxPos = 1;
                   infile.close();
                   out.close();
              } else {
                   System.out.println("file not found, program terminating");
                   System.exit(0);
    }thanks for all your help.
    bp

  • Blank Lines at end of file when using Variable Substitution in File Adapter

    Hi all,
    I'm using variable substitution in a File Adapter, it's refers an element of message, like:
    filename    payload:MESSAGE_INTERFACE,1,FILENAME,1
    The variable substitution is working right, but it's append a BLANK LINE at end of file.
    Anyone knows how to solve this problem ?
    Thanks in advance.

    Hi Regis,
    I suppose you're using content conversion?
    if so try adding
    <b>endSeparator</b> = '0'
    to your last element
    this will delete the default line break at the end
    Regards,
    michal
    <a href="/people/michal.krawczyk2/blog/2005/06/28/xipi-faq-frequently-asked-questions">XI FAQ - Frequently Asked Questions</a>

  • How to edit/modify a line of a text file using java io

    Hi every body
    I am new 2 java
    I am struck in editing a text file that ends with .dat
    I successfully added,viewed data of the *.dat file.
    but,I cannt edit,delete the lines that i need to do randomly.
    Here is the code i have written.
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.LineNumberReader;
    import java.io.RandomAccessFile;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    public class ReadWriteFile {
         String id=null;
         String name=null;
         String dept=null;
         String doj=null;
         String adrss=null;
         public void WriteFile(String Id,String Name,String Dept,String Doj,String Adrss) throws IOException{
              File f=new File("TraineeDetails.dat");
             if(!f.exists()){
             f.createNewFile();
              BufferedWriter bw=new BufferedWriter(new FileWriter("TraineeDetails.dat",true));
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              System.out.print("Enter Id : ");
              Id=br.readLine();
              System.out.print("Enter name : ");
              Name=br.readLine();
              System.out.print("Enter dept : ");
              Dept=br.readLine();
              System.out.print("Enter doj : ");
              Doj=br.readLine();
              System.out.print("Enter adrss : ");
              Adrss=br.readLine();
              bw.write(Id+"::"+Name+"::"+Dept+"::"+Doj+"::"+Adrss+":END:");
              bw.flush();
              bw.newLine();
              bw.close();
         public static void main(String[] args) throws IOException {
              ReadWriteFile rwf=new ReadWriteFile();
              String TID = null;
              String TADRSS = null;
              String TDOJ = null;
              String TNAME = null;
              String TDEPT = null;
              rwf.ReadFile(TID,TNAME,TDEPT,TDOJ,TADRSS);
         public void ReadFile(String Id1,String Name1,String Dept1,String Doj1,String Adrss1) throws IOException{
              BufferedReader br = new BufferedReader(new FileReader("TraineeDetails.dat"));
              String s;
               while((s = br.readLine())!= null)
                 // Create string tokenizer
                    StringTokenizer st =new StringTokenizer(s, "::");
                      System.out.println("----------------------------------------------");
                      System.out.println("| Trainee Id: "+st.nextToken()             +"|");
                      System.out.println("| Trainee Name: "+st.nextToken()           +"|");
                      System.out.println("| Trainee Department:"+st.nextToken()      +"|");
                      System.out.println("| Date of Joining: "+st.nextToken()        +"|");
                      System.out.println("| Trainee Address: "+st.nextToken()        +"|\n");
                      System.out.println("----------------------------------------------");
               // Close file reader
               br.close();
    }     and here is the data i have written
    Trainee.dat*
    111::jain::roads::2-2008::Blore:END:
    123::tim::service::1-2000::delhi:END:
    444::faru::civil::3-2200::sanapur:END:
    555::niv::cse::10-2000::gnagar:END:
    999::linda::mech::6-2001::tnagar:END:
    258::yansi::geo::8-2002::rtnagar:END:
    656::hari::garrage::3-1000::uttarahalli:END:
    888::muni::hr::5-2009::ernakulam:END:
    007::bond::spy::2-1972::america:END:
    0123::landy::games::6-2003::hdp:END:
    678::maddy::pumbing::4-1999::dispur:END:

    kalanidhi2u wrote:
    I want to randomly access the file
    But i cannt access itmake it RandomAccessFile... RandomAccessFile
    I edited it
    but i cannt edit the file by using itBoth of these are contradictory.

  • Add line to a text file just after a specific line with PowerShell

    Hi,
    I have to edit remotely a file called nsclient.ini on hundreds of computers, the file contains some command definitions. For example:
    [/settings/external scripts/scripts]
    check_event="C:\Program Files\NSClient++\scripts\Eventlog.exe" -e System -t Error
    check_event_application="C:\Program Files\NSClient++\scripts\Eventlog.exe" -e Application -t Error
    check_activedir=cscript "C:\Program Files\NSClient++\scripts\Check_AD.vbs" //nologo
    I need to add a new line just beneath [/settings/external scripts/scripts] This new line should not overwrite the existing lines beneath.
    Thanks for your help.

    @Blindrood
    The script does not work:
    Method invocation failed because [System.Char] does not contain a method named 'Trim'.
    At line:8 char:5
    +                 $List.($Element[0].Trim()) = $Element[1].Trim()
    +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : MethodNotFound
    Besides it changed totally my file (it added the required string but moved the string to the top of the file and removed all the other lines of the original file.
    Original File:
    # If you want to fill this file with all avalible options run the following command:
    # nscp settings --generate --add-defaults --load-all
    # If you want to activate a module and bring in all its options use:
    # nscp settings --activate-module <MODULE NAME> --add-defaults
    # For details run: nscp settings --help
    ; Undocumented section
    [/modules]
    ; CheckDisk - CheckDisk can check various file and disk related things. The current version has commands to check Size of hard drives and directories.
    CheckDisk = 1
    ; Event log Checker. - Check for errors and warnings in the event log. This is only supported through NRPE so if you plan to use only NSClient this wont help you at all.
    CheckEventLog = 1
    ; Check External Scripts - A simple wrapper to run external scripts and batch files.
    CheckExternalScripts = 1
    ; Helper function - Various helper function to extend other checks. This is also only supported through NRPE.
    CheckHelpers = 1
    ; Check NSCP - Checkes the state of the agent
    CheckNSCP = 1
    ; CheckSystem - Various system related checks, such as CPU load, process state, service state memory usage and PDH counters.
    CheckSystem = 1
    ; CheckWMI - CheckWMI can check various file and disk related things. The current version has commands to check Size of hard drives and directories.
    CheckWMI = 1
    ; NRPE server - A simple server that listens for incoming NRPE connection and handles them.
    NRPEServer = 1
    ; NSClient server - A simple server that listens for incoming NSClient (check_nt) connection and handles them. Although NRPE is the preferred method NSClient is fully supported and can be used for simplicity or for compatibility.
    NSClientServer = 1
    ; Undocumented section
    [/settings/default]
    ; ALLOWED HOSTS - A comaseparated list of allowed hosts. You can use netmasks (/ syntax) or * to create ranges.
    allowed hosts = 10.1.1.13
    [/settings/external scripts/scripts]
    check_event="C:\Program Files\NSClient++\scripts\Eventlog.exe" -e System -t Error
    check_event_application="C:\Program Files\NSClient++\scripts\Eventlog.exe" -e Application -t Error
    check_activedir=cscript "C:\Program Files\NSClient++\scripts\Check_AD.vbs" //nologo
    check_time=cscript.exe //T:30 //NoLogo "C:\Program Files\NSClient++\scripts\check_time.vbs" remrootvdc03 +5 +10
    ; A list of aliases available. An alias is an internal command that has been "wrapped" (to add arguments). Be careful so you don't create loops (ie check_loop=check_a, check_a=check_loop)
    [/settings/external scripts/alias]
    ; alias_cpu - Alias for alias_cpu. To configure this item add a section called: /settings/external scripts/alias/alias_cpu
    alias_cpu = checkCPU warn=80 crit=90 time=5m time=1m time=30s
    ; alias_cpu_ex - Alias for alias_cpu_ex. To configure this item add a section called: /settings/external scripts/alias/alias_cpu_ex
    alias_cpu_ex = checkCPU warn=$ARG1$ crit=$ARG2$ time=5m time=1m time=30s
    ; alias_disk - Alias for alias_disk. To configure this item add a section called: /settings/external scripts/alias/alias_disk
    alias_disk = CheckDriveSize MinWarn=10% MinCrit=5% CheckAll FilterType=FIXED
    ; alias_disk_loose - Alias for alias_disk_loose. To configure this item add a section called: /settings/external scripts/alias/alias_disk_loose
    alias_disk_loose = CheckDriveSize MinWarn=10% MinCrit=5% CheckAll FilterType=FIXED ignore-unreadable
    ; alias_event_log - Alias for alias_event_log. To configure this item add a section called: /settings/external scripts/alias/alias_event_log
    alias_event_log = CheckEventLog file=application file=system MaxWarn=1 MaxCrit=1 "filter=generated gt -2d AND severity NOT IN ('success', 'informational') AND source != 'SideBySide'" truncate=800 unique descriptions "syntax=%severity%: %source%: %message% (%count%)"
    ; alias_file_age - Alias for alias_file_age. To configure this item add a section called: /settings/external scripts/alias/alias_file_age
    alias_file_age = checkFile2 filter=out "file=$ARG1$" filter-written=>1d MaxWarn=1 MaxCrit=1 "syntax=%filename% %write%"
    ; alias_file_size - Alias for alias_file_size. To configure this item add a section called: /settings/external scripts/alias/alias_file_size
    alias_file_size = CheckFiles "filter=size > $ARG2$" "path=$ARG1$" MaxWarn=1 MaxCrit=1 "syntax=%filename% %size%" max-dir-depth=10
    ; alias_mem - Alias for alias_mem. To configure this item add a section called: /settings/external scripts/alias/alias_mem
    alias_mem = checkMem MaxWarn=80% MaxCrit=90% ShowAll=long type=physical type=virtual type=paged type=page
    ; alias_process - Alias for alias_process. To configure this item add a section called: /settings/external scripts/alias/alias_process
    alias_process = checkProcState "$ARG1$=started"
    ; alias_process_count - Alias for alias_process_count. To configure this item add a section called: /settings/external scripts/alias/alias_process_count
    alias_process_count = checkProcState MaxWarnCount=$ARG2$ MaxCritCount=$ARG3$ "$ARG1$=started"
    ; alias_process_hung - Alias for alias_process_hung. To configure this item add a section called: /settings/external scripts/alias/alias_process_hung
    alias_process_hung = checkProcState MaxWarnCount=1 MaxCritCount=1 "$ARG1$=hung"
    ; alias_process_stopped - Alias for alias_process_stopped. To configure this item add a section called: /settings/external scripts/alias/alias_process_stopped
    alias_process_stopped = checkProcState "$ARG1$=stopped"
    ; alias_sched_all - Alias for alias_sched_all. To configure this item add a section called: /settings/external scripts/alias/alias_sched_all
    alias_sched_all = CheckTaskSched "filter=exit_code ne 0" "syntax=%title%: %exit_code%" warn=>0
    ; alias_sched_long - Alias for alias_sched_long. To configure this item add a section called: /settings/external scripts/alias/alias_sched_long
    alias_sched_long = CheckTaskSched "filter=status = 'running' AND most_recent_run_time < -$ARG1$" "syntax=%title% (%most_recent_run_time%)" warn=>0
    ; alias_sched_task - Alias for alias_sched_task. To configure this item add a section called: /settings/external scripts/alias/alias_sched_task
    alias_sched_task = CheckTaskSched "filter=title eq '$ARG1$' AND exit_code ne 0" "syntax=%title% (%most_recent_run_time%)" warn=>0
    ; alias_service - Alias for alias_service. To configure this item add a section called: /settings/external scripts/alias/alias_service
    alias_service = checkServiceState CheckAll
    ; alias_service_ex - Alias for alias_service_ex. To configure this item add a section called: /settings/external scripts/alias/alias_service_ex
    alias_service_ex = checkServiceState CheckAll "exclude=Net Driver HPZ12" "exclude=Pml Driver HPZ12" exclude=stisvc
    ; alias_up - Alias for alias_up. To configure this item add a section called: /settings/external scripts/alias/alias_up
    alias_up = checkUpTime MinWarn=1d MinWarn=1h
    ; alias_updates - Alias for alias_updates. To configure this item add a section called: /settings/external scripts/alias/alias_updates
    alias_updates = check_updates -warning 0 -critical 0
    ; alias_volumes - Alias for alias_volumes. To configure this item add a section called: /settings/external scripts/alias/alias_volumes
    alias_volumes = CheckDriveSize MinWarn=10% MinCrit=5% CheckAll=volumes FilterType=FIXED
    ; alias_volumes_loose - Alias for alias_volumes_loose. To configure this item add a section called: /settings/external scripts/alias/alias_volumes_loose
    alias_volumes_loose = CheckDriveSize MinWarn=10% MinCrit=5% CheckAll=volumes FilterType=FIXED ignore-unreadable
    ; default - Alias for default. To configure this item add a section called: /settings/external scripts/alias/default
    default =
    File modified:
    [/settings/external scripts/scripts]
    check_disk_c=cscript.exe //NoLogo //T:10 "C:\Program Files\NSClient++\scripts\check_disk.wsf" /drive:"C:\" /w:3072 /c:1024
    CheckDisk=1
    CheckEventLog=1
    CheckExternalScripts=1
    CheckHelpers=1
    CheckNSCP=1
    CheckSystem=1
    NRPEServer=1
    NSClientServer=1
    allowed hosts=10.1.1.13
    ; A list of scripts available to run from the CheckExternalScripts module. Syntax is: <command>=<script> <arguments>
    check_event="C:\Program Files\NSClient++\scripts\Eventlog.exe" -e System -t Error
    check_event_application="C:\Program Files\NSClient++\scripts\Eventlog.exe" -e Application -t Error
    check_activedir=cscript "C:\Program Files\NSClient++\scripts\Check_AD.vbs" //nologo
    check_disk_c=cscript.exe //NoLogo //T:10 "C:\Program Files\NSClient++\scripts\check_disk.wsf" /drive:"c:\" /w:3072 /c:1024
    check_disk_d=cscript.exe //NoLogo //T:10 "C:\Program Files\NSClient++\scripts\check_disk.wsf" /drive:"d:\" /w:3072 /c:1024
    check_disk_e=cscript.exe //NoLogo //T:10 "C:\Program Files\NSClient++\scripts\check_disk.wsf" /drive:"e:\" /w:3072 /c:1024
    check_disk_f=cscript.exe //NoLogo //T:10 "C:\Program Files\NSClient++\scripts\check_disk.wsf" /drive:"f:\" /w:3072 /c:1024
    check_domain_admins=cscript.exe //NoLogo //T:10 "C:\Program Files\NSClient++\scripts\chk_group.wsf" /group:"Domain Admins"
    check_time=cscript.exe //T:30 //NoLogo "C:\Program Files\NSClient++\scripts\check_time.vbs" remrootvdc03 +5 +10
    max size=10000
    ; A list of aliases available. An alias is an internal command that has been "wrapped" (to add arguments). Be careful so you don't create loops (ie check_loop=check_a, check_a
    alias_cpu=checkCPU warn
    alias_cpu_ex=checkCPU warn
    alias_disk=CheckDriveSize MinWarn
    alias_disk_loose=CheckDriveSize MinWarn
    alias_event_log=CheckEventLog file
    alias_file_age=checkFile2 filter
    alias_file_size=CheckFiles "filter
    alias_mem=checkMem MaxWarn
    alias_process=checkProcState "$ARG1$
    alias_process_count=checkProcState MaxWarnCount
    alias_process_hung=checkProcState MaxWarnCount
    alias_process_stopped=checkProcState "$ARG1$
    alias_sched_all=CheckTaskSched "filter
    alias_sched_long=CheckTaskSched "filter
    alias_sched_task=CheckTaskSched "filter
    alias_service=checkServiceState CheckAll
    alias_service_ex=checkServiceState CheckAll "exclude
    alias_up=checkUpTime MinWarn
    alias_updates=check_updates -warning 0 -critical 0
    alias_volumes=CheckDriveSize MinWarn
    alias_volumes_loose=CheckDriveSize MinWarn

  • How to add a blank line in configurat​ion file

    Hi,
    I would like to add an empty / blank line in my configuration file. (.ini file) as below:
    [H1]
    key1=1
    [H2]
    key2=2
    I don't have any idea on how to add the empty/blank line.
    Could anyone help me on this? 

    In case you do not have such luxury, like me... 
    This example VI show an alternative way of inserting empty line/ space between sections of a configuration file...
    PS1: Note that Additional Empty Element is intentionally added to create/ add empty line/ space between sections... 
    Ian F
    Since LabVIEW 5.1... 7.1.1... 2009, 2010
    依恩与LabVIEW
    LVVILIB.blogspot.com
    Attachments:
    IFFCT_CFIO_example add empty line between sections.vi ‏64 KB

  • Find line number in text file

    Hi all,
    I need to find the line numbers on a file where a particular string matches.
    for example:
    A lazy cat
    A strong cat and it is black
    Black is not good
    So I will match for the word black and it will give the numbers say line 2 and 3 it found the match.
    I am using the code:
    try{
        // Open the file that is the first
        // command line parameter
          FileInputStream fstream = new FileInputStream("c:\\test.log");
        // Get the object of DataInputStream
          DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));
          String strLine;
         String[] arr= null;
        //Read File Line By Line
       String regex = "black";
       while ((strLine = br.readLine()) != null)   {
        // Split the sentence into strings based on space
           arr = strLine.split("\\s");
       if (arr[0].equalsIgnoreCase("black"))
          System.out.print("match found");
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(strLine);Thanks in advance.

    camellia wrote:
    I need to find the line numbers on a file where a particular string matches. Then declare a variable for line count. Find where you read in a line. Finally increment this variable each time a line is read.
    It isn't rocket science.
    Mel

  • Reading a Random Line from a Text File

    Hello,
    I have a program that reads from a text file words. I currently have a text file around 800KB of words. The problem is, if I try to load this into an arraylist so I can use it in my application, it takes wayy long to load. I was wondering if there was a way to just read a random line from the text file.
    Here is my code, and the text file that the program reads from is called 'wordFile'
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class WordColor extends JFrame{
         public WordColor(){
              super("WordColor");
              setSize(1000,500);
              setVisible(true);
              add(new WordPanel());
         public static void main(String[]r){
              JFrame f = new WordColor();
    class WordPanel extends JPanel implements KeyListener{
         private Graphics2D pane;
         private Image img;
         private char[]characterList;
         private CharacterPosition[]positions;
         private int charcounter = 0;
         private String initialWord;
         private File wordFile = new File("C:\\Documents and Settings\\My Documents\\Java\\projects\\WordColorWords.txt");
         private FontMetrics fm;
         private javax.swing.Timer timer;
         public final static int START = 20;
         public final static int delay = 10;
         public final static int BOTTOMLINE = 375;
         public final static int buffer = 15;
         public final static int distance = 4;
         public final static Color[] colors = new Color[]{Color.red,Color.blue,Color.green,Color.yellow,Color.cyan,
                                                                          Color.magenta,Color.orange,Color.pink};
         public static String[] words;
         public static int descent;
         public static int YAXIS = 75;
         public static int SIZE = 72;
         public WordPanel(){
              words = readWords();
              setLayout(new BorderLayout());
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              setFocusable(true);
              addKeyListener(this);
              timer = new javax.swing.Timer(delay,new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        YAXIS += 1;
                        drawWords();
                        if (YAXIS + descent - buffer >= BOTTOMLINE) lose();
                        if (allColorsOn()) win();
         public void paintComponent(Graphics g){
              super.paintComponent(g);
              if (img == null){
                   img = createImage(getWidth(),getHeight());
                   pane = (Graphics2D)img.getGraphics();
                   pane.setColor(Color.white);
                   pane.fillRect(0,0,getWidth(),getHeight());
                   pane.setFont(new Font("Arial",Font.BOLD,SIZE));
                   pane.setColor(Color.black);
                   drawThickLine(pane,getWidth(),5);
                   fm = g.getFontMetrics(new Font("Arial",Font.BOLD,SIZE));
                   descent = fm.getDescent();
                   distributePositions();
                   drawWords();
                   timer.start();
              g.drawImage(img,0,0,this);
         private void distributePositions(){
              int xaxis = START;
              positions = new CharacterPosition[characterList.length];
              int counter = 0;
              for (char c: characterList){
                   CharacterPosition cp = new CharacterPosition(c,xaxis, Color.black);
                   positions[counter] = cp;
                   counter++;
                   xaxis += fm.charWidth(c)+distance;
         private void drawThickLine(Graphics2D pane, int width, int thickness){
              pane.setColor(Color.black);
              for (int j = BOTTOMLINE;j<BOTTOMLINE+1+thickness;j++){
                   pane.drawLine(0,j,width,j);
         private void drawWords(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              drawThickLine(pane,getWidth(),5);
              for (CharacterPosition cp: positions){
                   int x = cp.getX();
                   char print = cp.getChar();
                   pane.setColor(cp.getColor());
                   pane.drawString(""+print,x,YAXIS);
              repaint();
         private boolean allColorsOn(){
              for (CharacterPosition cp: positions){
                   if (cp.getColor() == Color.black) return false;
              return true;
         private Color randomColor(){
              int rand = (int)(Math.random()*colors.length);
              return colors[rand];
         private void restart(){
              charcounter = 0;
              for (CharacterPosition cp: positions){
                   cp.setColor(Color.black);
         private void win(){
              timer.stop();
              newWord();
         private void newWord(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              repaint();
              drawThickLine(pane,getWidth(),5);
              YAXIS = 75;
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              distributePositions();
              charcounter = 0;
              drawWords();
              timer.start();
         private void lose(){
              timer.stop();
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              pane.setColor(Color.red);
              pane.drawString("Sorry, You Lose!",50,150);
              repaint();
              removeKeyListener(this);
              final JPanel p1 = new JPanel();
              JButton again = new JButton("Play Again?");
              p1.add(again);
              add(p1,"South");
              p1.setBackground(Color.white);
              validate();
              again.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        remove(p1);
                        addKeyListener(WordPanel.this);
                        newWord();
         private String getWord(){
              int rand = (int)(Math.random()*words.length);
              return words[rand];
         private String[] readWords(){
              ArrayList<String> arr = new ArrayList<String>();
              try{
                   BufferedReader buff = new BufferedReader(new FileReader(wordFile));
                   try{
                        String line = null;
                        while (( line = buff.readLine()) != null){
                             line = line.toUpperCase();
                             arr.add(line);
                   finally{
                        buff.close();
              catch(Exception e){e.printStackTrace();}
              Object[] objects = arr.toArray();
              String[] words = new String[objects.length];
              int count = 0;
              for (Object o: objects){
                   words[count] = (String)o;
                   count++;
              return words;
         public void keyPressed(KeyEvent evt){
              char tempchar = evt.getKeyChar();
              String character = ""+tempchar;
              if (character.equalsIgnoreCase(""+positions[charcounter].getChar())){
                   positions[charcounter].setColor(randomColor());
                   charcounter++;
              else if (evt.isShiftDown()){
                   evt.consume();
              else{
                   restart();
              drawWords();
         public void keyTyped(KeyEvent evt){}
         public void keyReleased(KeyEvent evt){}
    class CharacterPosition{
         private int xaxis;
         private char character;
         private Color color;
         public CharacterPosition(char c, int x, Color col){
              xaxis = x;
              character = c;
              color = col;
         public int getX(){
              return xaxis;
         public char getChar(){
              return character;
         public Color getColor(){
              return color;
         public void setColor(Color c){
              color = c;
    }

    I thought that maybe serializing the ArrayList might be faster than creating the ArrayList by iterating over each line in the text file. But alas, I was wrong. Here's my code anyway:
    class WordList extends ArrayList<String>{
      long updated;
    WordList readWordList(File file) throws Exception{
      WordList list = new WordList();
      BufferedReader in = new BufferedReader(new FileReader(file));
      String line = null;
      while ((line = in.readLine()) != null){
        list.add(line);
      in.close();
      list.updated = file.lastModified();
      return list;
    WordList wordList;
    File datFile = new File("words.dat");
    File txtFile = new File("input.txt");
    if (datFile.exists()){
      ObjectInputStream input = new ObjectInputStream(new FileInputStream(datFile));
      wordList = (WordList)input.readObject();
      if (wordList.updated < txtFile.lastModified()){
        //if the text file has been updated, re-read it
        wordList = readWordList(txtFile);
        ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
        output.writeObject(wordList);
        output.close();
    } else {
      //serialized list does not exist--create it
      wordList = readWordList(txtFile);
      ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
      output.writeObject(wordList);
      output.close();
    }The text file contained one random sequence of letters per line. For example:
    hwnuu
    nhpgaucah
    zfbylzt
    hwnc
    gicgwkhStats:
    Text file size: 892K
    Serialized file size: 1.1MB
    Time to read from text file: 795ms
    Time to read from serialized file: 1216ms

  • Delete lines from a text file

    i need to delete (or replace them with white space) a few lines from a text file. I have a text file with first few lines & last few lines containing "<"or ">". I need to delete/replace with white space, the entire line. i need to do this urgently
    Could some one please tell me how to do this?

    the file can be of size 8MB or more. i get this file
    every week from a third party. So the size is not
    constant. I need to remove/replace with white space,
    the fist & last few lines and the rest is comma
    seperated values which i need to load to database
    using sqlldr. But still not sure abt how to remove
    the first few lines.
    i need to read this file, replace the lines as i read
    them and write the replaced string back to the file &
    then load the rest of lines to database.8 MByte is fairly small. Read the file a line at a time and copy to a new file only the lines you want. Should take no more than a second or so.
    P.S. It will probably be a mistake if you try to edit the original file in place.

  • Different amount of read lines depending on whether file is open or closed with OleDbDataReader and OLEDB.12

    Reading the same Excel file with OleDbDataReader and the following connectionString:
    conn.ConnectionString =
    "Data Source='" + xlsxFile +
    "';Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";
    I would like to  start reading Excel file at line X, I skip X-1 first lines and:
    If file is closed, first row I get is the X+1 line.
    Instead, if file is open, with exactly the same source code, I get Xth line!
    I’m working with .net 2.0, Visual Studio 2008 and Microsoft Office Standard 2010.
    Do you have any clue? Thank you in advance!
    Mary

    Hi mary4wpf,
    I tested the code, and shown the excel data, it works well. the showing method is like below.
    if (datareader.HasRows)
    while (datareader.Read())
    if (skipLine)
    for (int j = 1; j < startIndex; j++)
    datareader.Read();
    skipLine = false;
    string L0="";
    string L1 = "";
    if (datareader.IsDBNull(0))
    L0 = "";
    else
    L0 = datareader.GetString(0);
    if (datareader.IsDBNull(1))
    L1 = "";
    else
    L1 = datareader.GetString(1);
    Console.WriteLine("{0}\t{1}", L0,L1);
    else
    Console.WriteLine("No rows found.");
    datareader.Close();
    If you have something weird, could you please share the weird with us? we could help you better.
    Regards,
    Youjun Tang
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • CLIENT_TEXT_IO : cannot insert new line into a text file

    Facts:
    Developer 10g
    AS 10g
    Web utility
    Problem:
    i am traying to
    Open a text file. using CLIENT_TEXT_IO.FOPEN
    insert a record in to a text file using CLIENT_TEXT_IO.PUTF
    insert a new line using chr(10) or CLIENT_TEXT_IO.NEW_LINE
    or CLIENT_TEXT_IO.put_line
    insert the next record
    Close the file.
    all work except insert a new line
    Why !!!
    it was Working fine in 6i, but now in 10g and Webutil is not working
    plz help

    Hi you can put a new line in a text file using System.getProperty("line.separator"). This implementation will work for every OS.
    import java.io.*;
    class Demo{
    public static void main(String args[]) throws Exception {
    FileWriter fr = new FileWriter("FileDemo.txt");
         fr.write("AAAAAAAAAA");
    fr.write(System.getProperty("line.separator"));
    fr.write("AAAAAAAAAAA");
    fr.close();
    }

  • Adding Schedule lines to a sales order

    Friends,
      We have a requirement to clear the old un-delivered scheduled lines from a sales order and then add new schedule lines from a EXCEL file.  We were able to clear the old by putting in a new location.  Then, when we go to enter the new schedule lines, it clears the location, marks the Fixed date and Qty, and enters the delivery dates and confirmed quantities.  We tried using BAPI_SALESORDER_CHANGE, but the schedule_lines table only has the required quantity so when used it increases the order quantity, which is not good.  Is there any Function module that we can call to insert new schedule lines without increasing the order quantity other than using a BDC?  Thanks!

    Pasted below is the BAPI documentation for this parameter.
    "Check Table for Schedule Lines
    Description
    This parameter completes the following two tasks:
    Controls processing functions with the value in the UPDATEFLAG field (change indicator).
    The following entries are available:
    ' ':   Create new schedule lines
    I:     Create new schedule lines
    U:     Change existing schedule lines
    D:     Delete existing schedule lines
    Controls the field entry with check fields
    If the UPDATEFLAG field has been activated, the system only copies those fields to the data parameter that have been filled with 'X'."
    Nabheet

  • Reading one line from a text file into an array

    i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
    public static void readAndProcessData(FileInputStream stream){
         InputStreamReader iStrReader = new InputStreamReader (stream);
         BufferedReader reader = new BufferedReader (iStrReader);
         String line = "";          
         try{
         int i = 0;
              while (line != null){                 
                   names[i] = reader.readLine();
                   score[i] = reader.readLine();
                   line = reader.readLine();
                   i++;                
              }catch (IOException e){
              System.out.println("Error in file access");
    this section calls it:
    try{                         
         FileInputStream stream = new FileInputStream("ISU.txt");
              HighScore.readAndProcessData(stream);
              stream.close();
              names = HighScore.getNames();
              scores = HighScore.getScores();
         }catch(IOException e){
              System.out.println("Error in accessing file." + e.toString());
    it gives me an array index out of bounds error

    oh wait I see it when I looked at the original quote.
    They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens.

  • Best way to remove last line-feed in text file

    What is the best way to remove last line-feed in text file? (so that the last line of text is the last line, not a line-feed). The best I can come up with is: echo -n "$(cat file.txt)" > newfile.txt
    (as echo -n will remove all trailing newline characters)

    What is the best way to remove last line-feed in text file? (so that the last line of text is the last line, not a line-feed). The best I can come up with is: echo -n "$(cat file.txt)" > newfile.txt
    (as echo -n will remove all trailing newline characters)
    According to my experiments, you have removed all line terminators from the file, and replaced those between lines with a space.
    That is to say, you have turned a multi-line file into one long line with no line terminator.
    If that is what you want, and your files are not very big, then your echo statement might be all you need.
    If you need to deal with larger files, you could try using the 'tr' command, and something like
    tr '
    ' ' ' <file.txt >newfile.txt
    The only problem with this is, it will most likely give you a trailing space, as the last newline is going to be converted to a space. If that is not acceptable, then something else will have to be arranged.
    However, if you really want to maintain a multi-line file, but remove just the very last line terminator, that gets a bit more complicated. This might work for you:
    perl -ne '
    chomp;
    print "
    " if $n++ != 0;
    print;
    ' file.txt >newfile.txt
    You can use cat -e to see which lines have newlines, and you should see that the last line does not have a newline, but all the others still do.
    I guess if you really did mean to remove all newline characters and replace them with a space, except for the last line, then a modification of the above perl script would do that:
    perl -ne '
    chomp;
    print " " if $n++ != 0;
    print;
    ' file.txt >newfile.txt
    Am I even close to understanding what you are asking for?

Maybe you are looking for

  • Ntsc hi8 to fce1, shot in pal

    Has anyone had problems with capturing Hi 8 (SP) video on Final Cut Express? I seem to be able to pull the video up in the capture window but its lke jerky but looks ok on a external switchable monitor, it's a Samsung HI 8 SCL 700 NTSC 8mm, in the me

  • CS5 No sound playback with HD422 clips

    Hi, I installed CS5 Master parallel to my CS4 Master installation on a Windows 7 (64-bit) system. I opened a new HD422 project and imported HD422 1080i50 footage. If I play back the clips on the timeline or through the monitor I can't hear any sound.

  • How to remove PIE from Xperia C6902

    How do I remove Position independent executables from Xperia z1 so that I can root? I have tried flashing it from Emma but Emma does not support C6902 Plz help

  • HELP! How to remove Yahoo search from firefox 36.0.1? HELP!

    I guess I made a big mistake upgrading to FireFox 36.0.1! Nothing but grief since trying to remove the Yahoo search from this version. Didn't appreciate this version removing my default Home page tabs to use on startup. Looks like they are gone forev

  • HT1689 why can't i log onto my itunes accound?

    Why can't I log onto my ITunes account for my Ipad?