0

Say I have a file text.txt containing the following on a single line:

abc, def, ghi, jkl

I am trying to get a list of data within the file so myList will result in ["abc", "def", "ghi", "jkl"], but it isn't seem to be working:

String[] tokens;
try {
        Scanner scanner = new Scanner("text.txt");
        while (scanner.hasNext()) { tokens = scanner.nextLine().split(","); }
} catch (IOException e) {
        e.printStackTrace();
}
System.out.println(tokens.length); // Prints 1 instead of 4

And trying to print index 0-3 gives an out of bounds error (obviously because the length is just 1)

I then want to change the data in one of the index (in the array), and re-write/over-write it back to the file. I think this answer should work for that, but only after I can get my array right. https://stackoverflow.com/a/1016291/4669619

Edit: At the moment, I know my file only has 4 things separated by 3 commas, as shown in the sample text file.

Community
  • 1
  • 1
Ali
  • 558
  • 7
  • 28
  • Will I still be able to access any index of tokens? i.e. to change specific data, and to re-write it like "fooWriter.write(tokens[2]);" as shown in the linked SO question. – Ali Apr 27 '15 at 06:06
  • @JBNizet How will I save, modify, and access data (and get length) with that? – Ali Apr 27 '15 at 06:10
  • @Ali you'll read the javadoc of List, and see that it has a method size(), and a method get(int index). – JB Nizet Apr 27 '15 at 06:14

5 Answers5

3

you are overwriting tokens for each line (I think you have a blank line)

try

String[] tokens;
try {
    scanner = new Scanner(new File ("text.txt"));
    while (scanner.hasNextLine())       // change this
    { 
         tokens = scanner.nextLine().split(","); 
         System.out.println(tokens.length); 
     }
} catch (IOException e) {
    e.printStackTrace();
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
2

Edit: You are not reading the text.txt file. with new Scanner("text.txt") you are using constructor Scanner(String source)`, while what you want is Scanner(File source)

I think this is what you are looking for using ArrayList:

ArrayList<String> tokens = new ArrayList<String>();
try {
        File file = new File("text.txt");
        Scanner scanner = new Scanner(file);
        while (scanner.hasNext()) { 
            String[]  str= scanner.nextLine().split(",");
            for(int i=0;i<str.length;i++){
                tokens.add(str[i]);
            }
        }
} catch (IOException e) {
        e.printStackTrace();
}
System.out.println(tokens.size());
DnR
  • 3,487
  • 3
  • 23
  • 31
0

Your code suggests that your loop will run until the END of file, and return the last line from file. Can you check if this is what you need? Maybe your last line does not contain ",".

Aakash
  • 2,029
  • 14
  • 22
0

Thanks for the valuable input guys, but I believe I have solved my problem:

String[] tokens;
try {
    Scanner scanner = new Scanner("text.txt");
    tokens = scanner.nextLine().split(",");
} catch (IOException e) {
    e.printStackTrace();
}

I will select this as the correct answers if I get a few up votes to show that my solution is indeed (one of the) correct one!

Ali
  • 558
  • 7
  • 28
  • @scary wombat already edited his post and make it correct 13 minutes before you posted yours. now I feels that you are not appreciate his effort to help you :\ – Baby Apr 27 '15 at 07:04
  • It's not that I am not appreciative. There was a gap between when I last checked for answers, and when when I posted mine. My editor was open for a while, so that might have been why I didn't see it. I have accepted his answer as the selected one. – Ali Apr 27 '15 at 13:08
-2

When you declare an array, you need to specify its size. Then you can assign a token into a specific position on your array.

String[] myStringArray = new String[3];
myStringArray[0] = "sample string";

Your problem is you dont really know exactly how many elements your array will contain. So the best solution is to use an ArrayList

ArrayList<String> myStringArrayList = new ArrayList<String>();
myStringArrayList.add("sample string");

try to incorporate that in your code.

jmcg
  • 1,547
  • 17
  • 22
  • *When you declare an array, you need to specify its size* - Not necessary. You just declare a *reference* which can point to an array object. – TheLostMind Apr 27 '15 at 06:10
  • You don't have to specify the size of array when declaring. As @TheLostMind had told, it's just a reference. – Aakash Apr 27 '15 at 06:11
  • At the moment, I know my array will contain 4 things separated by 3 commas (as shown in the sample text file example) – Ali Apr 27 '15 at 06:15
  • I may have used the wrong wording. point taken. What i meant was when you create a new instance of an Array, you have to either specify the array size, and/or specify the array elements. – jmcg Apr 27 '15 at 06:27
  • @jmcg the OP doesn't create any array. He's declaring a variable of type String[]. What is creating and returning the array is the split() method. – JB Nizet Apr 27 '15 at 06:45