7

I know how to read a file with Java using Scanner and File IOException, but the only thing I don't know is how to store the text in the files as an array.

Here is a snippet of my code:

 public static void main(String[] args) throws IOException{
    // TODO code application logic here

    // // read KeyWestTemp.txt

    // create token1
    String token1 = "";

    // for-each loop for calculating heat index of May - October


    // create Scanner inFile1
    Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt"));

    // while loop
    while(inFile1.hasNext()){

        // how can I create array from text read?

        // find next line
        token1 = inFile1.nextLine();

Here is what my KeyWestTemp.txt file contains:

70.3,   70.8,   73.8,   77.0,   80.7,   83.4,   84.5,   84.4,   83.4,   80.2,   76.3,   72.0   
Aruna
  • 11,959
  • 3
  • 28
  • 42
word word
  • 447
  • 3
  • 7
  • 9

7 Answers7

16

Stored as strings:

public class ReadTemps {

    public static void main(String[] args) throws IOException {
    // TODO code application logic here

    // // read KeyWestTemp.txt

    // create token1
    String token1 = "";

    // for-each loop for calculating heat index of May - October

    // create Scanner inFile1
    Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");

    // Original answer used LinkedList, but probably preferable to use ArrayList in most cases
    // List<String> temps = new LinkedList<String>();
    List<String> temps = new ArrayList<String>();

    // while loop
    while (inFile1.hasNext()) {
      // find next line
      token1 = inFile1.next();
      temps.add(token1);
    }
    inFile1.close();

    String[] tempsArray = temps.toArray(new String[0]);

    for (String s : tempsArray) {
      System.out.println(s);
    }
  }
}

For floats:

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class ReadTemps {

  public static void main(String[] args) throws IOException {
    // TODO code application logic here

    // // read KeyWestTemp.txt

    // create token1

    // for-each loop for calculating heat index of May - October

    // create Scanner inFile1
    Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");


    // Original answer used LinkedList, but probably preferable to use ArrayList in most cases
    // List<Float> temps = new LinkedList<Float>();
    List<Float> temps = new ArrayList<Float>();

    // while loop
    while (inFile1.hasNext()) {
      // find next line
      float token1 = inFile1.nextFloat();
      temps.add(token1);
    }
    inFile1.close();

    Float[] tempsArray = temps.toArray(new Float[0]);

    for (Float s : tempsArray) {
      System.out.println(s);
    }
  }
}
rainkinz
  • 10,082
  • 5
  • 45
  • 73
  • `new LinkedList();` what justifies the use of a linkedlist in this case? – njzk2 Nov 03 '14 at 14:06
  • @njzk2 Hmm, I don't think there is a good reason for it. ArrayList would probably be preferable unless there were a unknown large number of temperatures being added to the list. Updated my answer. – rainkinz Nov 03 '14 at 15:17
  • I think that good example should also close the `inFile1` Scanner (and thus the input file). It doesn't matter if this is all you do in `main` but in a bigger applicaiton it might become an issue. – SergGr Mar 01 '17 at 22:53
2

Just read the whole file into a StringBuilder, then split the String by dot following a space. You will get a String array.

Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt"));

StringBuilder sb = new StringBuilder();
while(inFile1.hasNext()) {
    sb.append(inFile1.nextLine());
}

String[] yourArray = sb.toString().split(", ");
Uwe Allner
  • 3,399
  • 9
  • 35
  • 49
Utku Özdemir
  • 7,390
  • 2
  • 52
  • 49
2

If you don't know the number of lines in your file, you don't have a size with which to init an array. In this case, it makes more sense to use a List :

List<String> tokens = new ArrayList<String>();
while (inFile1.hasNext()) {
    tokens.add(inFile1.nextLine());
}

After that, if you need to, you can copy to an array :

String[] tokenArray = tokens.toArray(new String[0]);
njzk2
  • 38,969
  • 7
  • 69
  • 107
1
while(inFile1.hasNext()){

    token1 = inFile1.nextLine();

    // put each value into an array with String#split();
    String[] numStrings = line.split(", ");

    // parse number string into doubles 
    double[] nums = new double[numString.length];

    for (int i = 0; i < nums.length; i++){
        nums[i] = Double.parseDouble(numStrings[i]);
    }

}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
0
int count = -1;
String[] content = new String[200];
while(inFile1.hasNext()){

    content[++count] = inFile1.nextLine();
}

EDIT

Looks like you want to create a float array, for that create a float array

int count = -1;
Float[] content = new Float[200];
while(inFile1.hasNext()){

    content[++count] = Float.parseFloat(inFile1.nextLine());
}

then your float array would look like

content[0] = 70.3
content[1] = 70.8
content[2] = 73.8
content[3] = 77.0 and so on
Ankit Rustagi
  • 5,539
  • 12
  • 39
  • 70
  • crashes as soon as there are more than 200 lines in the file. what's with the preincrementation anyway ? count will contain the number of read lines - 1 .... – njzk2 Nov 07 '13 at 19:18
  • Yes 200 was an assumption, i would usually store the content in one single array. Yes count would store the number of lines read. – Ankit Rustagi Nov 07 '13 at 19:20
  • in your case, no, count is 0 when 1 line was read. `i would usually store the content in one single array`. i didn't understand that part. – njzk2 Nov 07 '13 at 19:22
  • That would be pretty obvious, i keep count so that it would help in for loops in future if the need be. – Ankit Rustagi Nov 07 '13 at 19:25
0

I have found this way of reading strings from files to work best for me

String st, full;
full="";
BufferedReader br = new BufferedReader(new FileReader(URL));
while ((st=br.readLine())!=null) {
    full+=st;
}

"full" will be the completed combination of all of the lines. If you want to add a line break between the lines of text you would do full+=st+"\n";

Elipzer
  • 901
  • 6
  • 22
  • this is incredibly slow even on small files in the 100kb-1mb range. you can see some stats here http://stackoverflow.com/a/17757230/347508 use a stringbuilder instead! – kritzikratzi Mar 20 '16 at 17:20
0

I use this method:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class TEST {
    static Scanner scn;

public static void main(String[] args) {
    String text = "";

    try{
        scn = new Scanner(new File("test.txt"));
    }catch(FileNotFoundException ex){System.out.println(ex.getMessage());}
    while(scn.hasNext()){
        text += scn.next();
        }
        String[] arry = text.split(",");

    //if need converting to float do this:
    Float[] arrdy = new Float[arry.length];
    for(int i = 0; i < arry.length; i++){
            arrdy[i] = Float.parseFloat(arry[i]);
        }
    System.out.println(Arrays.toString(arrdy));
            }
}
Ayakashi
  • 11
  • 1
  • Why do you use `Scanner` to read file in a pre-splitted way just to join parts and split them again? What's the reason to add such answer to 3-years old question without any new good ideas? Please also note that there are other "bad smells" in your code. Why `scn` is a static member instead of just local variable? What happens if there was `FileNotFoundException`? (Hint: NullPointerException). Not closing Scanner is also not a good idea if this snippet would be used in a bigger application. – SergGr Mar 01 '17 at 22:52
  • where do you put 'test.txt' in the project structure to be found by just the name, looks like your not using a path? – Androidcoder Jan 28 '23 at 18:59