Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

File reading

Options
  • 03-10-2000 1:00pm
    #1
    Moderators, Social & Fun Moderators Posts: 28,633 Mod ✭✭✭✭


    stringTokeniser or something like that - it's been a while since I did any JAVA.



    All the best,

    Dav
    @B^)
    My page of stuff


Comments

  • Moderators, Social & Fun Moderators Posts: 10,501 Mod ✭✭✭✭ecksor


    import java.io.*;
    
    class FileSplit {
        public static void main(String args[]) {
            if( args.length < 1 ) {
                System.out.println("Usage: java FileSplit filename");
                System.exit(1);
            }
            String [] linelist = Splitter(args[0]);
            System.out.println("Lines read: " + linelist.length);
            for(int i = linelist.length - 1; i >= 0 ; i-- ) {
                System.out.println(linelist[i]);
            }
        }
    
        public static String [] Splitter(String filename) {
            int numlines = 32;
            int linesread = 0;
            String [] lines = null;
    
            try {
                BufferedReader fileinput = new BufferedReader(new FileReader(filename));
                lines = new String[numlines];
                while(fileinput.ready() ) {
                    lines[linesread] = fileinput.readLine();
                    linesread++;
                    if(linesread == numlines) {
                        String [] newarray = new String[numlines+32];
                        System.arraycopy(lines, 0, newarray, 0, numlines);
                        numlines += 32;
                        lines = newarray;
                    }
                }
            } catch (FileNotFoundException e) {
                System.out.println("File not found");
            } catch (IOException e ) {
            } finally {
                String [] newarray = new String [linesread];
                System.arraycopy(lines, 0, newarray, 0, linesread);
                lines = newarray;
            }
    
            return lines;
        }
    }
    

    reads in the file specified on the command line and spits it back out in reverse order (line wise that is). The method of creating a new array and using arraycopy seems messy to me, but I guess that's what the garbage collector is for. If anyone knows a better way of resizing an array, lemme know smile.gif


  • Closed Accounts Posts: 1,484 ✭✭✭El_Presidente


    (In Java) how do you read in a file and split it up into Strings so that each line of the original file becomes a String and the Strings are all held in an array?


Advertisement