John Preston
John Preston

Reputation: 19

Split text files

First of all I am new to Java.

I am trying to use the Split() function on a user specified txt file. It should split the files using space to output a array of Strings. I am using JFileChooser but I dont know how to perform Split on the selected txt file. I am using a Scanner to do this.

Please if someone can make the code finished, for some reason I cant get my head around it :-/

I have made it so far:

                JFileChooser chooser = new JFileChooser("C:\\");
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

            FileNameExtensionFilter filter = new FileNameExtensionFilter(
            ".txt and .java files", "txt", "java");
            chooser.setFileFilter(filter);


            int code = chooser.showOpenDialog(null);
            if (code == JFileChooser.APPROVE_OPTION) {
            File selectedFile = chooser.getSelectedFile();
            Scanner input;
            try {
                input = new Scanner(selectedFile);

                while (input.hasNext()) {

                String[] splits = input.next().split(" ");
                } 
                } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 


}
            }

Upvotes: 1

Views: 1095

Answers (4)

rgettman
rgettman

Reputation: 178343

If you need to split the input by the space character, then include a string with a space instead of an empty string. Replace

String[] splits = f.split("");

with

String[] splits = f.split(" ");  // One space

As others have pointed out, f isn't declared in your block. You'll have to declare it as a String and use your Scanner to read input into f, then use split.

Upvotes: 2

tckmn
tckmn

Reputation: 59363

    while (input.hasNext()) {

        String[] splits = f.split("");

        input.next();
    }

    System.out.println(f);

First of all, splits is never used. Second of all, input.next() is never stored in a variable. Also, I have no idea what f is. Try something like this:

    while (input.hasNext()) {

        String[] splits = input.next().split(" ");
        someList.add(splits);

    }

You could declare someList as something like new ArrayList<String[]>().

Upvotes: 0

Cyrille Ka
Cyrille Ka

Reputation: 15533

What is f? It's not declared anywhere, except as an Exception after having being used earlier, which makes no sense.

Your while loop should be written as this:

while (input.hasNextLine()) {

    String line = input.nextLine();
    String[] splits = line.split(" ");
    // put the result of split somewhere
}

Upvotes: 0

Mike Thomsen
Mike Thomsen

Reputation: 37524

f.split("");

or

f.split("[\\s]+");

to be safe with tabs and double spaces.

Upvotes: 0

Related Questions